gpt4 book ai didi

javascript - 如何使用正则表达式验证表单上的输入文件名?

转载 作者:行者123 更新时间:2023-11-28 16:36:03 25 4
gpt4 key购买 nike

我需要验证 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

我的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;

给你。问题是您将 .+ 放在开头的顺序错误,并且不应该封装 jpg/gif/png 和 [] 中的点。现在,正则表达式应该适用于 *.jp(e)g*.gif*.png。我还在列表中添加了 jpeg 并使正则表达式不区分大小写。

另外,请注意,它是 window 而不是 windows,并且 f.immagine.style 是一个对象,而不是字符串,因此请使用一些东西就像f.immagine.style.color = "#f00";

此外,您必须确保用户输入图像,因为任何具有修改后的扩展名的文件都会通过此测试。

关于javascript - 如何使用正则表达式验证表单上的输入文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4007979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com