0

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...

 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:

form  onsubmit="return valida(this)" action="inserisci_articolo1.php" enctype="multipart/form-data" method="post">
    input type="file" name="immagine" id="immagine" /
/form
3
  • What is your question? What exactly doesn't work? Commented Oct 24, 2010 at 11:18
  • What about .jpeg? or .PNG? Commented Oct 24, 2010 at 11:19
  • when i clic on the submit button of the form with an incorrect file (for example a txt file) the function have to "block" the link and to color the text of the file name in red, but seem that don't enter in the "if" and "else" block... Commented Oct 24, 2010 at 11:25

1 Answer 1

4
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.

Sign up to request clarification or add additional context in comments.

1 Comment

jpe?g saves you one alternation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.