Reputation: 460
Email address not validating completely for example. i have a email field and i am validating it from jQuery validation plugin. when i put some like "abbcss" it says email is not valid. then i put "abbcss@g" the error is gone and as you can see the email is still not valid. for better understanding i put a fiddle here.
$(document).ready(function(e) {
$('#email').keyup(function(){
$('#checkform').validate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="//cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.js"></script>
<form id="checkform">
<input id="email" type="email" name="email">
</form>
<hr>
<p>Try to put first "abcc" and click outside field </p>
<p>then try to put "abcc@gmail" and click outside field </p>
<p>it will consider it a valid email but actually it is not.</p>
any help regarding this issue will be appriciate.
Upvotes: 12
Views: 8907
Reputation: 1845
Except for testing if there is a value present prior to validating, this is the exact same code posted in the two other answers. In my case, I have an optional email field that I want to validate, but only if an email address is entered.
$.validator.addMethod("OptionalButValidEmail", function (value, element) {
// only test for email address validity if something is entered
if (value.length > 1) {
if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
return true;
} else {
return false;
}
} else {
return true;
}
}, "Please enter a valid Email.");
Upvotes: 1
Reputation: 616
$.validator.addMethod(
'validateEmail',
function(value, element) {
return (
this.optional(element) ||
/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(
value
)
);
},
'Please enter a valid email address.'
);
$('#form').validate({
rules: {
email: {
validateEmail: true,
},
});
Upvotes: 0
Reputation: 595
You can validate email by using jquery validation plugin add method
jQuery.validator.addMethod("validate_email", function(value, element) {
if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
return true;
} else {
return false;
}
}, "Please enter a valid Email.");
$('#checkform').validate({
rules: {
email: {
validate_email: true
},
}
});
Upvotes: 19