0

I need to validate the value of an e-mail input. I have this code but it doesn't work. Could you help me please?

HTML

<input type="text" name="mail" class="mail" /> 
<button class="validate">VALIDATE</button>

JQUERY

$(document).ready(function(){
    var setMail = $(".mail").val();
    var mailVal = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; 

    $(".validate").click(function(){
        if (mailVal == setMail) {
            alert("GOOD!");
            }
            else{ 
            alert("WRONG!");
            }
   });
});

JSFiddle: DEMO

2
  • 1
    Edit the following : if (mailVal.test(setMail)) { to if (mailVal.test($(".mail").val())) { because as of now setMail is only get at page load which will be empty so you are not validating anything. Commented Apr 23, 2015 at 18:55
  • You should restructure your code in a more efficient way and bind the input field to .focusout() this way you can do a validation without requiring a click button. Commented Apr 23, 2015 at 19:20

2 Answers 2

2

You can use jQuery validation library. It does many validation for you with an easy implementation way. Such like-

$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      email: true
    }
  }
});

documentation source link- jQuery Validation

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

Comments

1

mailVal isn't going to equal setMail. You want to check for a match: mailVal.test($(".mail").val()) instead of the == test.

1 Comment

I would also suggest that the input type be changed to "email" and the regex changed to be the following to follow W3C standards for email validation: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

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.