50

我正在尝试使用 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通过?

4

8 回答 8

97

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

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

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

于 2018-11-08T14:49:16.000 回答
34

>。更新。<

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


简单的反应验证器

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

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

例子

// 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)
  );
});

于 2019-04-26T10:53:32.550 回答
10

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

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

于 2019-01-04T06:29:15.247 回答
5

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"),

这对我最有效...您可以设置自己的长度...我只想要 10 位数字,不少于或更多

于 2020-08-08T16:00:29.357 回答
3

只是一点合作。就我而言,我不想验证输入是否为空(何时不需要)。谢谢大家的例子!

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
    })
})
于 2020-03-04T20:46:40.887 回答
1

我有一个类似的用例,这是我的解决方案:

// 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")
});
于 2020-05-27T09:01:16.137 回答
0

这是我的代码中的一个片段。

let schema = yup.object().shape({
  phone: yup
    .string()
    // regexr.com/6anqd
    .matches(/(\+91\ )[6-9]{1}[0-9 ]{4}[0-9 ]{4}[0-9]{3}/, {
      message: "Invalid Indian number",
      excludeEmptyString: false,
    })
    .required(),
  email: yup.string().required().email(),
  password: yup.string().required().min(8),
  confirmPassword: yup
    .string()
    .required()
    .oneOf([yup.ref("password")], "Passwords do not match"),
  agree: yup
    .boolean()
    .oneOf(
      [true],
      "It is essential to accept our Privacy Policy to register.",
    ),
});

我的正则表达式按照以下格式检查印度电话号码+91 axxx xxx xxx(其中a可以是 6 到 9 范围内的数字,x也可以是 0 - 9)。

我尝试了yup-home,但它无法真正验证我想要的印度号码的范围,另外,包裹导入大小很昂贵。


另外,我在前端使用带有 Formik 的 React 来使用react-phone-input-2进行表单验证

<PhoneInput
  country={"in"}
  value={values.phone}
  name="phone"
  onChange={(phone, data, e) => handleChange(e)}
  onBlur={(e) => handleBlur(e)}
  defaultMask=".... ... ..."
  masks={{ in: ".... ... ..." }}
  onlyCountries={["in"]}
  inputProps={{
    name: "phone",
    required: true,
    autoFocus: true,
  }}
  disableSearchIcon={true}
  disableDropdown={true}
  containerClass="mt-1 border h-12 text-sm focus:outline-none block w-full bg-gray-100 dark:bg-transparent border-transparent focus:bg-white"
  inputClass="mt-1 border h-12 text-sm focus:outline-none block w-full bg-gray-100 dark:bg-transparent border-transparent focus:bg-white"
  inputStyle={{
    background: "transparent",
    border: "1px solid grey",
    height: "3em",
    width: "100%",
    outline: "none",
  }}
  buttonStyle={{
    height: "3em",
    background: "transparent",
    outline: "none",
    border: "none",
  }}
/>
{handleFormikError(errors, touched, "phone")} // returns the span.alert with error message
于 2021-12-02T10:07:58.767 回答
0

我为此制作了一个名为yup-phone-lite的新软件包。我使用了原始的 yup-phone 包,但它使用了大量的 google-libphonenumber,所以我用一个较小的 fork 替换了它。

于 2021-06-04T01:45:07.417 回答