[英]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...我需要验证html表单中的输入文件是否为图像,我已经在html页面内制作了以下代码,但它不起作用......
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:我的html代码:
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 []
.问题是您将.+
以错误的顺序放在开头,并且不应该封装 jpg/gif/png 和[]
的点。 Now the regex should work for *.jp(e)g
, *.gif
and *.png
.现在正则表达式应该适用于*.jp(e)g
、 *.gif
和*.png
。 I also added jpeg
in the list and made the regex case-insensitive.我还在列表中添加了jpeg
并使正则表达式不区分大小写。
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";
另外,请注意它是window
不是windows
,并且f.immagine.style
是一个对象,而不是一个字符串,所以使用类似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.此外,您必须确保用户输入图像,因为任何具有修改扩展名的文件都将通过此测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.