views:

38

answers:

1

Hi, 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 don'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)) {
            windows.alert("espressione regolare corretta");
            return true;
        }
        else {
            windows.alert("espressione regolare non corretta");
            f.immagine.style = "color:#F00";
            return false;   
        }
    }
/script

...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
+4  A: 
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.

Gabi Purcaru
`jpe?g` saves you one alternation.
Tim Pietzcker
@Tim Pietzcker you are right. fixed
Gabi Purcaru