I need to verify that an input file in an html form is an image, I've made the follow code inside the html page, but it doesn't work...
script type="text/javascript" language="javascript"
function valida(f){
var campo = f.immagine.value;
//window.alert(campo);
var er = /^+.[\.]([jpg]|[gif]|[png])$/;
if(er.test(campo)) {
windows.alert("espressione regolare corretta");
return true;
}
else {
windows.alert("espressione regolare non corretta");
f.immagine.style = "color:#F00";
return false;
}
}
/script
My html code:
form onsubmit="return valida(this)" action="inserisci_articolo1.php" enctype="multipart/form-data" method="post">
input type="file" name="immagine" id="immagine" /
/form
var er = /^.+\.(jpe?g|gif|png)$/i;
There you go. The thing is that you put the .+
at the beginning in the wrong order, and should not have encapsulated jpg/gif/png and the point in []
. Now the regex should work for *.jp(e)g
, *.gif
and *.png
. I also added jpeg
in the list and made the regex case-insensitive.
Also, note that it's window
not windows
, and f.immagine.style
is an object, not a string, so use something like f.immagine.style.color = "#f00";
Also, you have to make sure the user inputs an image, because any file with modified extension will pass this test.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.