validation - 如何使用 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."),
});
解决方案
添加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}))
...
});
推荐阅读
- java - 从 Java 8 迁移后 Java 11 的内存问题
- javascript - Json 到 CSV 转换文件名无效
- node.js - 无法将消息上传到 Atlas 集群
- macos - 无法在 OSX 上的 Android Studio 中使用“包装小部件”功能
- parsing - Jackson在android中解析(ObjectMapping)
- node.js - 使用 xmlbuilder2 构建每组数据并将它们添加到呈现的 XML 页面
- java - 线程“main”java.lang.SecurityException 中的不明异常:Manifest 主要属性的签名文件摘要无效
- python-3.x - 当我在 MacOS 上同时安装了 python 3.7 和 3.8 时,如何删除 python 3.8?
- python - configparser.NoSectionError: No section: 'setting' PS C:\Users\p>
- wordpress - 使用 bookly wordpress 在 webex 中生成会议