I simply want to validate the filename of the image being uploaded to ensure that it does not have spaces or unusual characters.
This is my latest attempt from searching around, still no luck. Could it be something to do with the path of the file? is it taking this or just the file name into account?
I have this and a check of the extention working server side with php, but I would like a prompt to the user before submitting.
At this point in time im getting the alert pop up even whether i use a file name it should accept or one that it should reject.
JavaScript
function validate(elem){
var alphaExp = /^[a-zA-Z_-]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert("File name not suitable");
elem.focus();
return false;
}
}
HTML
<label for="file">Filename:</label>
<input type="file" name="filename" id="filename" onchange="validate(this)" />
<p><input type="submit" name="submit" class="submit" value="Submit" />
</form>
You will need to use a much more complex regular expression for this, because the elem.value you are checking won't be something like image123.jpg but more something like C:\fakepath\randomfolder\some other folder\image123.jpg
You might want to check into this : http://www.codeproject.com/Tips/216238/Regular-Expression-to-validate-file-path-and-exten
The exemple you'll find on this page is mostly for documents, not images, but you can twist it a bit to fit your needs like this :
^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(png|gif|jpg|jpeg)$
you can use this function too....
<script type="text/javascript">
function getNameFromPath(strFilepath) {
var objRE = new RegExp(/([^\/\\]+)$/);
var strName = objRE.exec(strFilepath);
if (strName == null) {
return null;
}
else {
return strName[0];
}
}
</script>
and
<script language="javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc") {
return true;
} else {
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
</script>
it is very very simple with test function
function validate(form){
if (/\s/.test(form.elements.file.value)) {
alert(' filename contains spaces. Please rename the file.');
return false;
}
return true;
}
<html>
<body>
<form onsubmit="return validate(this);">
<input type="file" name="file" value="" >
<input type="Submit" value="Submit" >
</form>
</body>
</html>
Source https://codehurdles.blogspot.in/2017/11/javascript-validate-filename-before.html
Related
I have 5 file inputs that I perform a file validation using the following code:
$("#fileinput").change(function() {
var file = this.files[0];
var fileType = file.type;
var match = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
if(!((fileType == match[0]) || (fileType == match[1]) || (fileType == match[2]) || (fileType == match[3]) || (fileType == match[4]) || (fileType == match[5]))){
Swal.fire("Erro: Invalid file format!", "Only: PDF, JPG, JPEG e PNG", "error");
$("#docpessoal").val(null);
$(".custom-file-label").text('Selecionar documento...');
return false;
}
});
Instead of repeating the function for each file input I would like to to use the same function but changing the selector ID based on which input the user clicked. (I'm not sure if it's possible)
Heres the code that I tried to do that:
var nomeInput = '_';
$('input[type="file"]').click(function(){
var nomeInput = $(this).attr('id');
});
I tried to use the variable nomeInput in the .change selector but it doesn't work.
Is there anyway to achieve that?
Delegate the change event to the form, in the handler, get a reference to the changed input via the event object, you don't need any messy identifiers or DOM traversing in the handler function. Like this:
$('.validate-form').on('change', '[type="file"]', e => {
const type = e.target.files[0].type;
if (!/application\/pdf|image\/jpe?g|image\/png/.test(type)) {
console.log('Filetype doesn\'t match.');
} else {
console.log('Accepted filetype.')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="validate-form">
<input name="dummy">
<br>
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
</form>
If the form contains file inputs you don't want to validate, group the wanted inputs with a class, and attach the listener using that class instead of more general attribute selector.
I am trying to get the filepath of the selected file.
Using the debugger, I see that the file has an property called value which is equal to : "C:\fakepath\filename.txt".
However when I try to access file.value, the filepath is equal to null.I am using Java 8, Struts 1.2, Jsps, and Chrome
Javascript:
function validateFile(file)
{
filepath = file.value; /*This is null*/
return true;
}
Html:
<input type="file" id="theFile[0]" onChange="validateFile(this)"/>
Try this:
function validateFile(fileinput) {
var allowed = "pdf,png";
var filepath=fileinput.value;
var ext = filepath.substr(filepath.lastIndexOf('.')+1);
if (filepath = "" || allowed.search(ext) <= -1) {
fileinput.value='';
alert('Invalid file type');
return false;
}
}
<input type="file" id="inputFile" onChange="validateFile(this)"/>
I guess it wasn't too much work after all :)
function validateFile(file)
{
filepath = file.value;
document.getElementById('result').innerText = filepath;
return true;
}
<input type="file" onChange="validateFile(this)"/>
<div id="result">[result will be here]</div>
I did a script that check the image width and remove the image if the width is lesser than certain amount.
The image field is required and after I removed it, it still passed the file validation.
sample: http://jsfiddle.net/AUQYv/3/
<form action="">
<input type="file" id="file" required />
<input type="submit" value="Submit">
</form>
Javascript
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
if(this.width<490||this.height<175){
$("#file").val("").change();
}
};
img.onerror = function () {
alert("not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Your conditional statement is setting file = this.files[0]. Change to ==
Edit:
Since both commenters pointed out that I was wrong, replace
$("#file").val("").change():
with
$("#file").replaceWith($("#file").clone());
Try with this.
<form action="" id="form" method="post">
<input type="file" id="file" required accept='image/png, image/gif, image/jpeg, image/jpg'/>
//your button submit
Submit
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//When click the button
$('#submitForm').click(function(){
var validation = true; //Var to validation true
if($('#file').val()){ //There's image?
if($('#file').width()<490 || $('#file').height()<175){
validation = false;
}
}else{
validation = false;
}
//Is true?
if(validation){
$('#form').submit();
}else{
alert("select a image");
}
});
</script>
I am checking the file size and extension of a file before it is uploaded, and (for the most part) the code is running correctly. However, I am unable to remove the disabled attribute from the submit button if the file has the correct extension and is under 2MB. I feel as if there is something minor I am not seeing or forgetting. I would appreciate any help or tips.
Thanks,
-Kyle
Here is my code:
<p>Select a logo to upload</p>
<input type="file" id="uploadFile" class="upload" name="upfile"><br>
<input type="submit" id="uploadSubmit" value="Upload Image" disabled="disabled">
document.getElementById("uploadFile").addEventListener("change", checkFile, true);
function checkFile(e) {
var files = e.target.files;
for (var i = 0, file; file = files[i]; i++) {
var fileName = file.name;
var fileExt = fileName.split(".")[fileName.split(".").length - 1].toLowerCase();
var fileSize = document.getElementById("uploadFile").files[0].size;
var fileSizeMB = (file.size / 2097152).toFixed(2);
if (!(fileExt === "jpg" || fileExt === "eps" || fileExt === "tif" || fileExt === "tiff") || fileSize > 2097152) {
alert("There is an error with the file you selected. Please check the file size and/or the file type.");
} else {
$("#uploadSubmit").prop("disabled", false);
}
}
};
Try
$("#uploadSubmit").removeAttr("disabled");
Hope it helps.
Sorry I can't just comment because it requires at least 50 reputation, wtf!
check if you have jQuery, I notice you're using getElementById at the beginning and somehow you're using jQuery selector for uplaodSubmit. Other than that, syntax looks correct to me.
And if you want to stick with pure JS, use:
document.getElementById('uploadSubmit').disabled = false
instead.
Good Luck.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="script/jquery-1.9.1.min.js"></script>
</head>
<script>
$(function() {
$('#uploadFile').bind('change', function() {
var filename = this.files[0].name.toLowerCase();
if ((filename.indexOf(".jpg") > -1)
|| (filename.indexOf(".png") > -1)) {
if(this.files[0].size<2000000){
$("#uploadSubmit").removeAttr("disabled");
alert("This is your solution");
}else{
alert("You cant get bigger than 2 MB");
}
} else {
alert("File format must jpg or png");
return false;
}
});
});
</script>
<body>
<p>Select a logo to upload</p>
<input type="file" id="uploadFile" class="upload" name="upfile"><br>
<input type="submit" id="uploadSubmit" disabled="disable" value="Upload Image">
</body>
I tried this I think this more helpful for you
$("#element").attr("disabled", false) OR $("#element").removeAttr("disabled").
I hope this first example is better with new jQuery version.
I can't figure out why this is not working as i did everything correct.
This is a simple create a account form. I put validation code for some of the field like name, email and password. There are many other fields. but first i m trying this.
The like is here:
jsfiddle
and the code of HTML:
First Name
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname />
<input type="text" name="remail" id="remail" />
New Pasword
<input type="password" name="rpass" id="rpass" />
<input name="regis" type="submit" class="color2" id="id" value="Submit" />
The javascript code here:
function validateRegis() {
//regex for fname and lname
var fname = $("#fname").val();
var lname = $("#lname").val();
var patt_n = /[a-z]{2,20}/i;
//checking fname and lname for regex matching
var ftest = patt_n.test(fname);
var ltest = patt_n.test(lname);
var remail = $("#remail").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9\_\.\-]+[a-zA-Z0-9\_\-]+#[a-zA-Z0-9]+[a-zA-Z0-9\.\-]+[a-zA-Z0-9]+\.[a-z]{2,4}$/;
var test = filter.test(remail);
var rpass = $("#rpass").val();
var patt = /[a-z0-9~!##$%^&*()_\ ]/i;
var test2 = patt.test(rpass);
if (fname === "" || ftest === false) {
alert("Please provide first name!");
$("#fname").focus();
return false;
} else if (lname === "" || ltest === false) {
alert("Please provide Last name!");
$("#lname").focus();
return false;
} else if (remail === "" || test === false) {
//
alert("Please provide email in correct format!");
$("#remail").focus();
return false;
} else if (rpass === "" || rpass.length < 8 || test2 === false) {
alert("Please provide password!");
$("#rpass").focus();
return false;
} else if ((fname !== "") & (lname !== "") & (remail !== "") & (test === true) & (rpass >= 8) & test2 === true) {
return true;
}
}
It needs jquery to run the code.
The problem is the validateRegis function is not available in the global scope.
In the fiddle UI left side panel, 2nd select box select No Wrap in body, it works fine.
Demo: Fiddle
When you select onLoad there, all the scripts under the script frame is wrapped under a anonymous function, so your validateRegis method becomes a local member of that anonymous function. Thus that function will not be available when the function submit is called causing an Uncaught ReferenceError: validateRegis is not defined error being thrown.