2

I'm doing validation first on an email(mandatory and correct format) and then on a file upload(either blank or correct format) on the button submit.
Here the email is validating well but in file upload if it is blank it also shows an error which is not needed.

Code:

<script type="text/javascript">

    $(document).ready(function () {

     $("#button").click(function () {

         var email = $("#person_email").val();
         var img = $("#person_avatar").val();

         if (email == null || email == "" || !email.match(/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/))

         {
             $("#valid").show();
             return false;

         } else if (!img == "" || !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/))

         {
             $("#valid_1").show();
             return false;
         } else {
             return true;
         }
     });
 });
</script>

3 Answers 3

3

Try to change

(!img == "" || !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/))

to

(!img == "" && !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/))
Sign up to request clarification or add additional context in comments.

Comments

2

Use and instead of or. Possibly also worth checking for null on this one as well:

...
} else if (img != null && img != "" && !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/)) {
     $("#valid_1").show();
     return false;
}

The problem is that you're saying "when it's not empty or it's an incorrect file format, show the error message". Since img == "" will fail the first condition, it falls to the second. Since "" is not one of your approved file types, it passes that test, and goes into the error code.

Instead, you need to say "when it's not empty and it's an incorrect file format, show the message". That way, when it's empty it fails the first test, so the entire condition fails.

As it was, it will have been entering the if block regardless of what you enter into the field - if it's empty then it's a wrong file type, but if it's not empty then it's not empty so it passes the first test.

Comments

1
(!img == "" || !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/))
(!img == "" && !img.match(/(\.bmp|\.png|\.jpg|\.jpeg|\.gif)$/))

Edit this.

Comments

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.