Reputation: 2377
I'm currently working on my own validation, but I have one small problem. I can't get email validation to work. I have tried some different expressions, but can't get it to work. Maybe i did something wrong with the layout?
var email = $('.email');
function valemail(){
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)){
return true;
} else {
return false;
}
}
$('#registerform').submit(function() {
if (valemail()) {
return true;
} else {
return false;
}
});
Upvotes: 1
Views: 2454
Reputation: 98718
I would not write my own validation script when the jQuery Validate plugin is available.
However, you could simply take a look at the email regex contained within it and use that...
function email(value) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
return /^((([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.test(value);
}
$('#registerform').submit(function() {
var result = email($('#myemailfield').val());
if (result) {
alert('passed'); // <-- your code if passed
} else {
alert('failed'); // <-- your code if failed
}
});
Simple Demo: http://jsfiddle.net/m8baZ/
Upvotes: 1
Reputation: 707198
When you do this:
var email = $('.email');
if (filter.test(email)){
email
is a jQuery object, not the string the user typed. You need to get the actual string out of the input field and use that with your regex like this:
if (filter.test(email.val())){
Upvotes: 0
Reputation:
Try this :
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
The the following calls:
$('#registerform').submit(function(){
if(IsEmail($(this).val())==false){
//do something validation not satisfied
}else{
//do something
}
});
Upvotes: 2