首页 > 解决方案 > 如何使用 Yup 验证电话号码但不是必需的?

问题描述

我能够验证是否使用此正则表达式键入了电话号码,但它需要在输入字段中输入电话号码。我正在尝试将电话号码设为可选。当我删除 .matches phoneRegExp 时,它可以在不需要的情况下工作。我相信这与使该字段变为必需的正则表达式有关。但我不确定。我应该以不同的方式做吗?谢谢


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

const signUpSchema = yup.object().shape({
  username: yup
    .string()
    .min(4, "Need at least 4 characters.")
    .required("Username is required"),
  firstName: yup
    .string()
    .min(2, "Need at least 2 characters.")
    .required("First name is required"),
  lastName: yup
    .string()
    .min(2, "Need at least 2 characters")
    .required("Last name is required"),
  email: yup
    .string()
    .email()
    .required("Email is required"),
  phoneNumber: yup.string()
    .matches(phoneRegExp, "Phone number is not valid")
    .notRequired(),
  password: yup
    .string()
    .min(6, "Password must be at least 6 characters.")
    .required("Password is required"),
  instructorOrClient: yup
    .string()
    .matches(/(instructor|client)/, "Either instructor or client.")
    .required("Please select instructor or client."),
});

标签: validationphone-numberyup

解决方案


添加excludeEmptyString:true到匹配项。必须是一个对象。

{
message:"Phone not valid",
excludeEmptyString:true
}

例子

  const PHONE_NO_REGEX = /^[0-9\- ]{8,14}$/
        const signUpSchema = yup.object().shape({
        ...
        phoneNumber: yup.string()
            .matches(PHONE_NO_REGEX, phoneNumber:yup.string().matches(PHONE_NO_REGEX,{message:"not valid phone no",excludeEmptyString:true}))
          
        ...
        });

推荐阅读