So I’m Trying to do a image validator with Javascript on a input[type="file"]. But with others validations it works perfectly. Everytime I blur the input when the value is valid, it returns false and true over and over. My goal is to have a good Input validation.
//Image Validator
const ImageExp = new RegExp(/.*.(jpe?g|png|)$/igm)
function ValidaImagem(x) {
if (ImageExp.test(x.value) == true) {
console.log(true);
x.style.background = "#0F0";
return true;
} else {
console.log(false);
x.style.background = "#F00";
return false;
}
}
document.getElementById("Photo").addEventListener("blur", function() {
ValidaImagem(document.getElementById("Photo"))
})
document.getElementById("Submit-btn").addEventListener("click", function() {
ValidaImagem(document.getElementById("Photo"))
})
<input type="file" accept="image/*" id="Photo" name="" class="form-control" />
<button id="Submit-btn">Submit</button>
2
Answers
Your image validation function tests the value property of the file input. However, the value of an input-type file will give you the file name but not the contents or the file type. Therefore, your regular expression is tested against the filename, not the file type. This might work if you always trust users to label their file types correctly, but it’s not foolproof and won’t validate the file’s actual content. You can fix this by changing your Regex to match the MIME type of the file like so,
Using this method, you can match and test against the
file.type
value by first capturing the contents of the submission. Which changes your validation program to this:Everything else in your HTML and CSS you can keep the same.
You can learn more about MIME types here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
Notice this specific section:
"Warning: Browsers use the MIME type, not the file extension, to determine how to process a URL, so it's important that web servers send the correct MIME type in the response's Content-Type header. If this is not correctly configured, browsers are likely to misinterpret the contents of files, sites will not work correctly, and downloaded files may be mishandled"
If the goal is only to submit the form if an image is selected it should be enough to set the
accept
attribute as you already did and therequired
attribute.