javascript - 使用 Yup 验证不需要的表单字段?
问题描述
我想用 Yup 验证一个不需要的表单字段
const validationSchema = Yup.object().shape({
firstname: Yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast ${min} alphabets`).max(20,`Should not exceed ${max} alphabets'),
lastname: Yup.string().nullable().notRequired()
})
lastname: Yup.string.nullable().notRequired()
. 我不知道如何继续进行,因为如果给出了输入,我有多个条件来验证该字段。
我的验证条件是:
- 应该只包含字母。
- 至少应包含 2 个字母,最多 20 个字母。
解决方案
match
你应该使用你已经拥有的类似模式firstname
。一种可能的方法是这样的:
const obj = {
firstname: 'my name',
lastname: 'asd'
};
const yupObj = yup.object().shape({
firstname: yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast 3 alphabets').max(20,`Should not exceed 20 alphabets`),
lastname: yup.string().nullable().notRequired().matches(/[a-zA-Z]{2,20}/, 'should have alphabets between 2 and 20')
})
yupObj
.validate(obj)
.then(function(value) {
console.log(value);
})
.catch(function(err) {
console.log(err);
});
推荐阅读
- bixby - 在 Bixby 中,有没有办法以特定顺序在图像选择器中显示图像或按图像名称对其进行排序?
- ios - 如何在滚动条上隐藏搜索栏?(没有 UITableViewController)
- machine-learning - 自然语言处理、机器学习、数据科学
- javascript - 有没有办法将视频数据从视频标签/MediaStream 发送到 OffscreenCanvas?
- bootstrap-4 - 导航栏链接之间的 Bootstrap 4 响应中心徽标
- string - 我从 api 将 Json 作为字符串返回,但在 javascript 的客户端上它以对象的形式出现
- android - 通过 CALL_PHONE 直接呼叫
- php - 多酒店预订系统的数据库设计/结构
- python - 我在这段代码中做错了什么我一直坚持
- php - PHP 通过电子邮件安全地发送 GET 请求