Reputation: 59
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!");
}
});
});
Upvotes: 0
Views: 67
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
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