How to verify an input file name on a form using regular expression?
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)) {
开发者_StackOverflow社区 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.
精彩评论