简体   繁体   English

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

[英]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.

相关问题 如何使用正则表达式验证Javascript中的字符串? - How to verify a string in Javascript using regular expression? Javascript正则表达式以验证表单验证 - Javascript regular expression to verify form validation 如何使用正则表达式验证此类输入? - How to validate such input using a regular expression? 如何使用jQuery将正则表达式应用于输入? - How to apply Regular Expression to input using jQuery? 如何使用正则表达式在输入元素的名称属性上调用 onclick 函数? - how to call onclick function on name attribute of an input element by using a regular expression? 如何在 javascript 中使用正则表达式在用户表单输入中只允许一个(破折号或点或下划线)? - How do i allow only one (dash or dot or underscore) in a user form input using regular expression in javascript? 如何使用正则表达式验证Java中的数字 - How to use regular expression to verify a number in Javascript 使用javascript中的正则表达式验证要在Windows中创建文件的文件名 - Validating file name for creating file in windows, using regular expression in javascript 使用Java中的正则表达式验证输入 - Verify an input using Regular Expressions in Javascript 使用任何基于Javascript的库查找文件名的正则表达式 - Regular expression to find file name using any Javascript based library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM