41
votes

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?

8
Hi Evans, it's disappointing that no one answered it. I have the same problem. did you find any solution?Mosijava

8 Answers

75
votes

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

28
votes

>. Update .<

http://yup-phone.js.org/

I've created a yup-phone module that uses google-libphonenumber which gives accurate validation checks and can be installed directly from github

npm install --save yup yup-phone.

Check Usage

const Yup = require('yup');
require('yup-phone');

// validate any phone number (defaults to India for country)
const phoneSchema = Yup.string().phone().required();
phoneSchema.isValid('9876543210'); // → true


From Simple React Validator,

The regex for phone number validation is

/^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/

Example

// index.js

const yup = require('yup');
const { rePhoneNumber } = require('./yup-phone')

const schema = yup.string().phone()

const phone = '+911234567890';
console.log('Is Valid? ', rePhoneNumber.test(phone)); // Is Valid? true
schema.validateSync(phone);

// yup-phone.js

const yup = require('yup');

const rePhoneNumber = /^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/;

module.exports.rePhoneNumber = rePhoneNumber

yup.addMethod(yup.string, "phone", function() {
  return this.test("phone", "Phone number is not valid", value =>
    rePhoneNumber.test(value)
  );
});

8
votes

Try this, it might be helpful for you.

mobile: Yup.string().matches(/^[6-9]\d{9}$/, {message: "Please enter valid number.", excludeEmptyString: false})

4
votes

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


phone_number: Yup.string()
  .required("required")
  .matches(phoneRegExp, 'Phone number is not valid')
  .min(10, "to short")
  .max(10, "to long"),

This works best for me...you can set your own length...i just wanted 10 digits not less or more

2
votes

Just a little collaboration. On my case I don't want to validate if the input is empty (when is not required). Thank you all for your examples!

yup.addMethod(yup.string, "phone", function(messageError = 'Phone number is not valid') {
    const phoneRegExp = /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/
    return this.test('phone', messageError, value => {
      if (value && value.length > 0) {
        return phoneRegExp.test(value)
      }
      return true
    })
})
1
votes

I have a similar use case, and here's my solution:

// Regex source: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html

const phoneRegex = RegExp(
  /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
);

const schema = yup.object().shape({
  phone: yup.string().matches(phoneRegex, "Invalid phone").required("Phone is required")
});
-1
votes

I made a new package for this called yup-phone-lite. I had used the original yup-phone package but it uses the massive google-libphonenumber so I replaced it with a smaller fork.

-2
votes

Yup.string().trim().required().matches(/^\d+$/, 'has incorrect format').length(10, 'must be 10 digits')