I have a form field that should accept either an email or a phone number. I already have this code to validate an email address:
function validateEmail(email)
{
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
But I also need to validate for a phone number that can only be in this format:
+XXX XXX XXX XXX || +XXXXXXXXXXXX || XXX XXX XXX || XXXXXXXXX
How do I add that validation, so that I either validate an email or a phone in that format? I'm sorry, I'm a javascript beginner. THANK YOU!
I already have this error message printing done:
if(!validateEmail(signup_email))
{
show_error_msg('error_signup_email','<?php _e( 'Enter a valid email address or a phone number' ); ?>');
jQuery("#signup_email").focus();
return false;
}
Progress: I added a function to validate the phone number:
function validatePhone(email)
{
var re = /^\+?([0-9]{3})\)?[ ]?([0-9]{3})[ ]?([0-9]{3})[ ]?([0-9]{3})$/;
return re.test(email);
}
And edited the Error message to this:
if((!validateEmail(signup_email)) || (!validatePhone(signup_email)))
{
show_error_msg('error_signup_email','<?php _e( 'Enter a valid email address or a phone number', 'Matrix' ); ?>');
jQuery("#signup_email").focus();
return false;
}
But the form stopped printing the success message and it says the phone number is invalid.
How about testing the phone number after you remove the spaces?
function validatePhone(phone)
{
var re = /^(\+\d{3})?\d{9}$/;
return re.test(phone.replace(/\s+/g, ''));
}
This regex is then an optional prefix of a plus symbol and 3 digits followed by 9 digits.
Combining this with some other tweaks, the following has been tested and works.
function validateEmail(email)
{
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if(!validateEmail(field) && !validatePhone(field))
{
show_error_msg('error_signup_email','Enter a valid email address or a phone number');
jQuery("#signup_email").focus();
return false;
}
Verification at http://jsfiddle.net/f2rL3pj0/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.