Petr Rajchert
Petr Rajchert

Reputation: 59

email input validation in Jquery

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

Upvotes: 0

Views: 67

Answers (2)

Barett
Barett

Reputation: 5948

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

Upvotes: 1

Khairul Islam
Khairul Islam

Reputation: 1215

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

Upvotes: 2

Related Questions