首页 > 解决方案 > 使用 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'),

.min(8)验证数字为 8 或更多。所以只要输入8就会通过。我怎样才能使需要 8 个字符才能1000 0000通过?

标签: javascriptyup

解决方案


嗨,现在我正在解决与您相同的问题,并且找到了可能的解决方案。

使用与正则表达式匹配的字符串验证电话号码

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')

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


推荐阅读