I\'m new to jQuery and was wondering how to use it to validate email addresses.
This performs a more thorough validation, for example it checks against successive dots in the username such as john..doe@example.com
function isValidEmail(email)
{
return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email)
&& /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email);
}
See validate email address using regular expression in JavaScript.
Bug is in Jquery Validation Validation Plugin Only validates with @ to change this
change the code to this
email: function( value, element ) {
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}
function validateEmail(emailaddress){
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailaddress)) {
alert("Please enter valid email id");
}
}
This regexp prevents duplicate domain names like abc@abc.com.com.com.com, it will allow only domain two time like abc@abc.co.in. It also does not allow statring from number like 123abc@abc.com
regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/,
All The Best !!!!!
The problem I came across while using Fabian's answer, is implementing it in an MVC view because of the Razor @
symbol. You have to include an additional @
symbol to escape it, like so: @@
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
I didn't see it elsewhere on this page, so I thought it might be helpful.
Here's a link from Microsoft describing it's usage.
I just tested the code above and got the following js:
function validateEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Which is doing exactly what it's supposed to do.
<script type = "text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type = "text/javascript">
function ValidateEmail(email) {
var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
$("#btnValidate").live("click", function () {
if (!ValidateEmail($("#txtEmail").val())) {
alert("Invalid email address.");
}
else {
alert("Valid email address.");
}
});
</script>
<input type = "text" id = "txtEmail" />
<input type = "button" id = "btnValidate" value = "Validate" />