带自定义输入选项的单选按钮Yup验证Schema跨字段逻辑实现问题
带自定义输入选项的单选按钮Yup验证Schema跨字段逻辑实现问题
嘿,我刚好之前处理过类似的单选+自定义输入的验证场景,Yup的when方法就是解决这种跨字段联动逻辑的核心!咱们一步步来搞定这个Schema:
首先,你的需求核心是两个互斥的分支:
- 选择常规选项时:
otherRadio必须为false,otherText必须为空 - 选择「Other」选项时:
regularOption必须为空,otherText必须满足5-20字符的长度要求
下面是完整的验证Schema实现,我会逐段解释:
import * as yup from 'yup'; const formSchema = yup.object().shape({ regularOption: yup.string() // 当otherRadio为false时,regularOption必须必填 .when('otherRadio', { is: false, then: (schema) => schema.required('请选择一个常规选项'), // 当otherRadio为true时,regularOption必须为空 otherwise: (schema) => schema.test( 'is-empty', '选择「Other」时不能同时选择常规选项', (value) => value === undefined || value === '' ) }), otherRadio: yup.boolean().default(false), otherText: yup.string() // 当otherRadio为true时,必须满足长度要求 .when('otherRadio', { is: true, then: (schema) => schema .required('请输入自定义内容') .min(5, '请至少输入5个字符') .max(20, '输入内容不能超过20个字符'), // 当otherRadio为false时,otherText必须为空 otherwise: (schema) => schema.test( 'is-empty', '未选择「Other」时不能输入自定义内容', (value) => value === undefined || value === '' ) }) });
关键逻辑说明:
when方法:Yup的when可以根据另一个字段的值来动态切换当前字段的验证规则,完美适配这种跨字段联动场景test自定义验证:对于「必须为空」的场景,用test方法比直接用nullable().notRequired()更严格,能确保用户不会在不该输入的地方填写内容- 互斥性保证:两个分支的验证规则互相约束,确保用户只能在「选常规选项」或「选Other+填文本」中二选一
另外,建议你在前端交互上也要配合这个逻辑:比如选中「Other」时才启用otherText输入框,未选中时禁用并清空内容,这样能减少用户触发验证错误的概率,但验证Schema本身还是要做严格校验,避免前端交互被绕过的情况。
备注:内容来源于stack exchange,提问作者noblerare




