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

时间:2010-10-24 11:16:49

标签: javascript regex

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

1 个答案:

答案 0 :(得分:4)

var er = /^.+\.(jpe?g|gif|png)$/i;

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

另请注意,window不是windowsf.immagine.style是对象,而不是字符串,因此请使用f.immagine.style.color = "#f00";

之类的内容

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