Validate phone number with Yup?
>. 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)
);
});
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
Try this, it might be helpful for you.
mobile: Yup.string().matches(/^[6-9]\d{9}$/, {message: "Please enter valid number.", excludeEmptyString: false})
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