如何使用Yup验证电话号码,但不是必需的?

时间:2020-04-28 01:08:01

标签: validation phone-number 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."),
});

2 个答案:

答案 0 :(得分:0)

您应该执行.nullable()

const signUpSchema = yup.object().shape({
...
phoneNumber: yup.string()
    .matches(phoneRegExp, "Phone number is not valid")
    .nullable(),
...
});

您可以在docs上了解有关此内容的更多信息。

答案 1 :(得分:0)

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