javascriptyup

Validate phone number with Yup?


I'm trying to validate a phone number with Yup:

phone: Yup.number()
  .typeError("That doesn't look like a phone number")
  .positive("A phone number can't start with a minus")
  .integer("A phone number can't include a decimal point")
  .min(8)
  .required('A phone number is required'),

.min(8) validates that the number is 8 or more. So simply entering 8 will pass. How can I make 8 characters required so 1000 0000 would pass?


Solution

  • Hi right now I'am solving same problem as you and I found possible solution.

    Validate phone number with string that matches Regex

    const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/
    
    phoneNumber: Yup.string().matches(phoneRegExp, 'Phone number is not valid')
    

    You can search for different Regex Expressions and validate it. I've used Regex from this article https://www.sitepoint.com/community/t/phone-number-regular-expression-validation/2204