I\'m new to jQuery and was wondering how to use it to validate email addresses.
<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>
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');
}
}
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:
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();
}}}}}}}}}
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. */ }
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();
});
}
});