I'm new to 开发者_开发技巧jQuery and was wondering how to use it to validate email addresses.
You can use regular old javascript for that:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
jQuery Function to Validate Email
I really don’t like to use plugins, especially when my form only has one field that needs to be validated. I use this function and call it whenever I need to validate an email form field.
function validateEmail($email) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
and now to use this
if( !validateEmail(emailaddress)) { /* do stuff here */ }
Cheers!
Look at http: //bassistance.de/jquery-plugins/jquery-plugin-validation/. It is nice jQuery plugin, which allow to build powerfull validation system for forms.
There are some usefull samples here. So, email field validation in form will look so:
$("#myform").validate({
rules: {
field: {
required: true,
email: true
}
}
});
See Email method documentation for details and samples.
I would use the jQuery validation plugin for a few reasons.
You validated, ok great, now what? You need to display the error, handle erasing it when it is valid, displaying how many errors total perhaps? There are lots of things it can handle for you, no need to re-invent the wheel.
Also, another huge benefit is it's hosted on a CDN, the current version at the time of this answer can be found here: http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx This means faster load times for the client.
<script type="text/javascript">
$(document).ready(function() {
$('.form_error').hide();
$('#submit').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var message = $('#message').val();
if(name== ''){
$('#name').next().show();
return false;
}
if(email== ''){
$('#email').next().show();
return false;
}
if(IsEmail(email)==false){
$('#invalid_email').show();
return false;
}
if(phone== ''){
$('#phone').next().show();
return false;
}
if(message== ''){
$('#message').next().show();
return false;
}
//ajax call php page
$.post("send.php", $("#contactform").serialize(), function(response) {
$('#contactform').fadeOut('slow',function(){
$('#success').html(response);
$('#success').fadeIn('slow');
});
});
return false;
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
</script>
<form action="" method="post" id="contactform">
<table class="contact-table">
<tr>
<td><label for="name">Name :</label></td>
<td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="form_error">Please enter your name</span></td>
</tr>
<tr>
<td><label for="email">Email :</label></td>
<td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="form_error">Please enter your email</span>
<span class="form_error" id="invalid_email">This email is not valid</span></td>
</tr>
<tr>
<td><label for="phone">Phone :</label></td>
<td class="phone"><input name="phone" id="phone" type="text" placeholder="Please enter your phone" class="contact-input"><span class="form_error">Please enter your phone</span></td>
</tr>
<tr>
<td><label for="message">Message :</label></td>
<td class="message"><textarea name="message" id="message" class="contact-input"></textarea><span class="form_error">Please enter your message</span></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" class="contactform-buttons" id="submit"value="Send" />
<input type="reset" class="contactform-buttons" id="" value="Clear" />
</td>
</tr>
</table>
</form>
<div id="success" style="color:red;"></div>
<!-- Dont forget to include the jQuery library here -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#validate").keyup(function(){
var email = $("#validate").val();
if(email != 0)
{
if(isValidEmailAddress(email))
{
$("#validEmail").css({
"background-image": "url('validYes.png')"
});
} else {
$("#validEmail").css({
"background-image": "url('validNo.png')"
});
}
} else {
$("#validEmail").css({
"background-image": "none"
});
}
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
</script>
<style>
#validEmail
{
margin-top: 4px;
margin-left: 9px;
position: absolute;
width: 16px;
height: 16px;
}
.text
{
font-family: Arial, Tahoma, Helvetica;
}
</style>
<title>Live Email Validation with jQuery Demo</title>
</head>
<body>
<div class="text"><h1>Reynoldsftw.com - Live Email Validation</h1><h2>Type in an email address in the box below:</h2></div>
<div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>
<div class="text"><P>More script and css style
: www.htmldrive.net
Source:htmldrive.com
- http://so.devilmaycode.it/jquery-validate-e-mail-address-regex/
- using new regex
- added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }
this was provided by user Luca Filosofi in this answer this answer
I would recommend Verimail.js, it also has a JQuery plugin.
Why? Verimail supports the following:
- Syntax validation (according to RFC 822)
- IANA TLD validation
- Spelling suggestion for the most common TLDs and email domains
- Deny temporary email account domains such as mailinator.com
So besides validation, Verimail.js also gives you suggestions. So if you type an email with the wrong TLD or domain that is very similar to a common email domain (hotmail.com, gmail.com, etc), it can detect this and suggest a correction.
Examples:
- test@gnail.con -> Did you mean test@gmail.com?
- test@hey.nwt -> Did you mean test@hey.net?
- test@hottmail.com -> Did you mean test@hotmail.com?
And so on..
To use it with jQuery, just include verimail.jquery.js on your site and run the function below:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
The message element is an element in which a message will be shown. This can be everything from "Your email is invalid" to "Did you mean ...?".
If you have a form and want to restrict it so that it cannot be submitted unless the email is valid, then you can check the status using the getVerimailStatus-function as shown below:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid
}else{
// Valid
}
This function returns an integer status code according to the object Comfirm.AlphaMail.Verimail.Status. But the general rule of thumb is that any codes below 0 is codes indicating errors.
Javascript Email Validation in MVC/ASP.NET
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: @@
To Avoid Razor In MVC
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.
EDIT
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.
As others have mentioned you can use a regex to check if the email address matches a pattern. But you can still have emails that match the pattern but my still bounce or be fake spam emails.
checking with a regex
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
checking with a real email validation API
You can use an API which will check if the email address is real and currently active.
var emailAddress = "foo@bar.com"
response = $.get("https://isitarealemail.com/api/email/validate?email=" +
emailAddress,
function responseHandler(data) {
if (data.status === 'valid') {
// the email is valid and the mail box is active
} else {
// the email is incorrect or unable to be tested.
}
})
For more see https://isitarealemail.com or blog post
A very simple solution is to use html5 validation:
<form>
<input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">
<input type="submit">
</form>
http://jsfiddle.net/du676/56/
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.
If you have a basic form, just make the input type of email:
<input type="email" required>
This will work for browsers that use HTML5 attributes and then you do not even need JS. Just using email validation even with some of the scripts above will not do much since:
some@email.com so@em.co my@fakemail.net
etc... Will all validate as "real" emails. So you would be better off ensuring that the user has to enter their email address twice to make sure that they put the same one in. But to guarantee that the email address is real would be very difficult but very interesting to see if there was a way. But if you are just making sure that it is an email, stick to the HTML5 input.
FIDDLE EXAMPLE
This works in FireFox and Chrome. It may not work in Internet Explorer... But internet explorer sucks. So then there's that...
function isValidEmail(emailText) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailText);
};
Use Like This :
if( !isValidEmail(myEmail) ) { /* do things if myEmail is valid. */ }
function validateEmail(emailaddress){
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailaddress)) {
alert("Please enter valid email id");
}
}
<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" />
Landed here.....ended up here: https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
...which provided the following regex:
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
...which I found thanks to a note on the jQuery Validation plugin readme: https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue
So, the updated version of @Fabian's answer would be:
function IsEmail(email) {
var regex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
return regex.test(email);
}
Hope that helps
This question is more dificult to answer than seems at first sight. If you want to deal with emails correctly.
There were loads of people around the world looking for "the regex to rule them all" but the truth is that there are tones of email providers.
What's the problem? Well, "a_z%@gmail.com cannot exists but it may exists an address like that through another provider "a__z@provider.com.
Why? According to the RFC: https://en.wikipedia.org/wiki/Email_address#RFC_specification.
I'll take an excerpt to facilitate the lecture:
The local-part of the email address may use any of these ASCII characters:
- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6] Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.
So, i can own an email address like that:
A__z/J0hn.sm{it!}h_comment@example.com.co
If you try this address i bet it will fail in all or the major part of regex posted all across the net. But remember this address follows the RFC rules so it's fair valid.
Imagine my frustration at not being able to register anywhere checked with those regex!!
The only one who really can validate an email address is the provider of the email address.
How to deal with, so?
It doesn't matter if a user adds a non-valid e-mail in almost all cases. You can rely on HTML 5 input type="email" that is running near to RFC, little chance to fail. HTML5 input type="email" info: https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html
For example, this is an RFC valid email:
"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
But the html5 validation will tell you that the text before @ must not contain " or () chars for example, which is actually incorrect.
Anyway, you should do this by accepting the email address and sending an email message to that email address, with a code/link the user must visit to confirm validity.
A good practice while doing this is the "enter your e-mail again" input to avoid user typing errors. If this is not enough for you, add a pre-submit modal-window with a title "is this your current e-mail?", then the mail entered by the user inside an h2 tag, you know, to show clearly which e-mail they entered, then a "yes, submit" button.
use this
if ($this.hasClass('tb-email')) {
var email = $this.val();
var txt = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!txt.test(email)) {
e.preventDefault();
$this.addClass('error');
} else {
$this.removeClass('error');
}
}
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 );
}
For thoose who want to use a better maintainable solution than disruptive lightyear-long RegEx matches, I wrote up a few lines of code. Thoose who want to save bytes, stick to the RegEx variant :)
This restricts:
- No @ in string
- No dot in string
- More than 2 dots after @
- Bad chars in the username (before @)
- More than 2 @ in string
- Bad chars in domain
- Bad chars in subdomain
- Bad chars in TLD
- TLD - addresses
Anyways, it's still possible to leak through, so be sure you combine this with a server-side validation + email-link verification.
Here's the JSFiddle
//validate email
var emailInput = $("#email").val(),
emailParts = emailInput.split('@'),
text = 'Enter a valid e-mail address!';
//at least one @, catches error
if (emailParts[1] == null || emailParts[1] == "" || emailParts[1] == undefined) {
yourErrorFunc(text);
} else {
//split domain, subdomain and tld if existent
var emailDomainParts = emailParts[1].split('.');
//at least one . (dot), catches error
if (emailDomainParts[1] == null || emailDomainParts[1] == "" || emailDomainParts[1] == undefined) {
yourErrorFunc(text);
} else {
//more than 2 . (dots) in emailParts[1]
if (!emailDomainParts[3] == null || !emailDomainParts[3] == "" || !emailDomainParts[3] == undefined) {
yourErrorFunc(text);
} else {
//email user
if (/[^a-z0-9!#$%&'*+-/=?^_`{|}~]/i.test(emailParts[0])) {
yourErrorFunc(text);
} else {
//double @
if (!emailParts[2] == null || !emailParts[2] == "" || !emailParts[2] == undefined) {
yourErrorFunc(text);
} else {
//domain
if (/[^a-z0-9-]/i.test(emailDomainParts[0])) {
yourErrorFunc(text);
} else {
//check for subdomain
if (emailDomainParts[2] == null || emailDomainParts[2] == "" || emailDomainParts[2] == undefined) {
//TLD
if (/[^a-z]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}
} else {
//subdomain
if (/[^a-z0-9-]/i.test(emailDomainParts[1])) {
yourErrorFunc(text);
} else {
//TLD
if (/[^a-z]/i.test(emailDomainParts[2])) {
yourErrorFunc(text);
} else {
yourPassedFunc();
}}}}}}}}}
You can use jQuery Validation and, in a single HTML line, you can validate the email and the email validation message: type="email" required data-msg-email="Enter a valid email account!"
You can use the data-msg-email parameter to place a personalized message or otherwise do not place this parameter and the default message will be displayed: "Please enter a valid email address."
Full example:
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script>
$("#commentForm").validate();
</script>
if($("input#email-address").getVerimailStatus() < 0) {
(incorrect code)
}
if($("input#email-address").getVerimailStatus() == 'error') {
(right code)
}
checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
Refernce : JQUERY UI WEBSITE
you should see this:jquery.validate.js,add it to your project
using it like this:
<input id='email' name='email' class='required email'/>
Another simple and complete option:
<input type="text" id="Email"/>
<div id="ClasSpan"></div>
<input id="ValidMail" type="submit" value="Valid"/>
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#ValidMail").click(function () {
$('span', '#ClasSpan').empty().remove();
if (IsEmail($("#Email").val())) {
//aqui mi sentencia
}
else {
$('#ClasSpan').append('<span>Please enter a valid email</span>');
$('#Email').keypress(function () {
$('span', '#itemspan').empty().remove();
});
}
});
You can create your own function
function emailValidate(email){
var check = "" + email;
if((check.search('@')>=0)&&(check.search(/\./)>=0))
if(check.search('@')<check.split('@')[1].search(/\./)+check.search('@')) return true;
else return false;
else return false;
}
alert(emailValidate('your.email@yahoo.com'));
A simplified one I've just made, does what I need it to. Have limited it to just alphanumeric, period, underscore and @.
<input onKeyUp="testEmailChars(this);"><span id="a"></span>
function testEmailChars(el){
var email = $(el).val();
if ( /^[a-zA-Z0-9_@.-]+$/.test(email)==true ){
$("#a").html("valid");
} else {
$("#a").html("not valid");
}
}
Made with help from others
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 !!!!!
Validate email while typing, with button state handling.
$("#email").on("input", function(){
var email = $("#email").val();
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!filter.test(email)) {
$(".invalid-email:empty").append("Invalid Email Address");
$("#submit").attr("disabled", true);
} else {
$("#submit").attr("disabled", false);
$(".invalid-email").empty();
}
});
精彩评论