如何使用Yup对非必填表单字段实现填写后的规则校验?
Yup非必填字段有值才验证的实现方案
你可以直接在lastname的验证规则后追加格式和长度验证规则,配合字段转换逻辑即可实现需求,完整验证schema如下:
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 at least ${min} alphabets`) .max(20, `Should not exceed ${max} alphabets`), lastname: Yup.string() .nullable() // 空字符串自动转null,命中非必填跳过验证的逻辑 .transform((value) => value?.trim() || null) .notRequired() .matches(/^[A-Za-z]+$/, "Last name should contain only alphabets") .min(2, `Last name should contain at least ${min} alphabets`) .max(20, `Last name should not exceed ${max} alphabets`) })
规则说明
transform((value) => value?.trim() || null):将用户输入的空白内容(全空格、空字符串)自动转换为null,避免空白内容触发后续验证notRequired()声明字段非必填,当值为null/undefined时,后续的格式、长度验证规则会自动跳过- 仅当用户实际输入了非空白内容时,后面的字母校验、长度校验规则才会生效
如果需要更显式的条件判断逻辑,也可以使用when方法实现:
lastname: Yup.string() .nullable() .trim() .notRequired() .when('lastname', { is: (value) => Boolean(value), then: (schema) => schema .matches(/^[A-Za-z]+$/, "Last name should contain only alphabets") .min(2, `Last name should contain at least ${min} alphabets`) .max(20, `Last name should not exceed ${max} alphabets`) })
内容的提问来源于stack exchange,提问作者Gnanavel
相关产品推荐
相关产品推荐

