用Yup验证电话号码?

Eva*_*nss 12 javascript yup

我正在尝试用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'),
Run Code Online (Sandbox Code Playgroud)

.min(8)验证该数字是否为8或更多.所以简单输入8就会通过.如何才能使8个字符需要1000 0000才会通过?

abh*_*ekp 28

>. 更新.<

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

我创建了一个yup-phone模块,用于google-libphonenumber提供准确的验证检查,并且可以直接从 github 安装

npm install --save yup yup-phone.

检查使用情况

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
Run Code Online (Sandbox Code Playgroud)

简单的反应验证器

电话号码验证的正则表达式是

/^(\+?\d{0,4})?\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{3}\)?)\s?-?\s?(\(?\d{4}\)?)?$/
Run Code Online (Sandbox Code Playgroud)

例子

// 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);
Run Code Online (Sandbox Code Playgroud)
// 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)
  );
});
Run Code Online (Sandbox Code Playgroud)

  • 我最初对此投了赞成票。然而,捆绑包的大小比我的整个网站还要大。不要在前端使用它 (3认同)

小智 21

嗨,现在我解决了和你一样的问题,我找到了可能的解决方案.

使用与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')
Run Code Online (Sandbox Code Playgroud)

您可以搜索不同的正则表达式并进行验证.我在本文中使用了Regex https://www.sitepoint.com/community/t/phone-number-regular-expression-validation/2204

  • `/^((\+[1-9]{1,4}[ -]?)|(\([0-9]{2,3}\)[ -]?)|([0-9] {2,4})[ -]?)*?[0-9]{3,4}[ -]?[0-9]{3,4}$/` 最适合我。@filippofilip你的表达匹配诸如+32---------1111111之类的东西 (5认同)

小智 12

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, "too short")
  .max(10, "too long"),
Run Code Online (Sandbox Code Playgroud)

这最适合我...你可以设置自己的长度...我只想要 10 位数字不少于或较多


Sir*_*sha 8

试试这个,它可能对你有帮助。

mobile: Yup.string().matches(/^[6-9]\d{9}$/, {message: "请输入有效号码。", excludeEmptyString: false})