1
\$\begingroup\$

I'd like to get a review on 2 regexes, one for email and one for phone validation.

/* Add jQuery validator method to check if phone numbers are in correct format.
   Use regex101.com for explaination of the regex.
   Using value.replace with / /g to remove all spaces. Normal replace with ' ' only works once. */
$.validator.addMethod('phone_number', function(value, element) {
    return /^\+(?:\d{1,3}|\d-\d{3}|\d{2}-\d{4})(?:\s?)\d{5,14}$/.test(value.replace(/ /g, ''));
});

/* Add jQuery validator method to check emails correctly.
   The original jQuery validator email method didn't correctly check double dots
   Eg. test..something@email.com worked while it's an invalid email.
 */
$.validator.methods.email = function(value, element) {
    return /^(?:(?:\w)+[._]?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$/gi.test(value.replace(/\\/g,'').trim());
};

Regexes only:

Phone: /^\+(?:\d{1,3}|\d-\d{3}|\d{2}-\d{4})(?:\s?)\d{5,14}$/

Email: /^(?:(?:\w)+[._]?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$/gi

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.