Validating phone numbers with yup -- googlelip, yup-phone, regex

Viewed 261

I have been trying to validate a phone number with yup.

I've tried a few regex examples

const phoneSchema = yup
  .string()
  .matches(phoneRegExp, "Phone number is not valid")
  .required();

fliflop

 /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/

LGenzelis

/^((\+[1-9]{1,4}[ -]?)|(\([0-9]{2,3}\)[ -]?)|([0-9]{2,4})[ -]?)*?[0-9]{3,4}[ -]?[0-9]{3,4}$/

and I've tried two libs yup-phone and google-libphonenumber

but I am unsure on what the matrix would be for valid and invalid phone number formats -- a QA flagged the initial validation in place because it would allow multiple + signs in front of the number +++12345 -- but the libs consider this valid. One of the regex seems to work well but then it will allow another + sign in the middle of the number +234+32432.

Also I am concerned about how to validate the number with google lib - if it could be any type of region -- the expected behaviour being they could enter UK/International or US numbers into the system -- would it be a case of detecting the region of the entered number and solving validation that way?

let region = "US";

  try {
    const number = phoneUtil.parseAndKeepRawInput(value, region);
    res = phoneUtil.isValidNumber(number).toString();
  } catch (e) {
    res = "false";
  }

//google lib phone https://codesandbox.io/s/google-phone-lib-demo-forked-k29kk8

//yup phone https://codesandbox.io/s/yup-phone-validation-forked-ixgnjj

//regex by flipflop https://codesandbox.io/s/regex-flipflop-phone-number-validation-forked-ggvel7

//regex by LGenzelis https://codesandbox.io/s/regex-lgens-phone-number-validation-forked-szuy6o

this is my number matrix -- but some of these seem to fall through the validation process

//valid numbers
Standard Telephone numbers
+61 1 2345 6789
+61 01 2345 6789 (zero entered is not required but enterd by user anyway)
01 2345 6789
01-2345-6789
(01) 2345 6789
(01) 2345-6789
1234 5678
1234-5678
12345678
Mobile Numbers
0123 456 789
0123456789
International Phone Numbers
US Format - +1 (012) 456 7890
US Virgin Islands (four digit international code) +1-340 123 4567

// invalid numbers
1234+5678
+++12345678
1 Answers

If you want to implement this in react front end You can use a validating function from react-phone-number-input npm package

 import { isValidPhoneNumber } from 'react-phone-number-input'

phone: Yup.string()
      .required("Phone number is required")
      .test("is-valid-phone", "Phone number is invalid", (value) => {
        return isValidPhoneNumber(value || '');
}),

Related