
本文介绍如何在 React + react-hook-form 项目中,借助 Yup 的 test 自定义验证方法,检查用户输入是否属于指定的白名单数组(如姓名列表),并配合错误提示实现精准表单校验。
本文介绍如何在 react + react-hook-form 项目中,借助 yup 的 `test` 自定义验证方法,检查用户输入是否属于指定的白名单数组(如姓名列表),并配合错误提示实现精准表单校验。
在基于 Yup 的表单验证中,内置的 .required()、.min() 等方法无法直接满足“值必须存在于某个数组中”的业务需求。此时,Yup 提供了灵活的 .test() 方法,允许你编写自定义同步校验逻辑。
以你的场景为例:需确保 firstname 输入值必须是 ['John', 'Paul', 'Mike', 'Adam'] 中的某一个。只需在 Yup Schema 中为 firstname 字段添加 .test() 验证器:
const names = ['John', 'Paul', 'Mike', 'Adam'];
const schema = yup.object().shape({
firstname: yup
.string()
.required('First Name Required')
.test({
name: 'in-names-array', // 可选:用于调试或区分多个 test
message: 'must be in names array!',
test: (value) => typeof value === 'string' && names.includes(value),
}),
});⚠️ 注意事项:
- 类型安全:value 可能为 undefined 或非字符串(尤其在字段为空时),因此建议先做类型判断(如 typeof value === 'string'),避免 includes 报错;
- 大小写敏感:names.includes(value) 区分大小写。若需忽略大小写,可改用 names.map(n => n.toLowerCase()).includes(value?.toLowerCase());
-
性能考量:对于大型数组,建议提前构建 Set
提升查找效率(const nameSet = new Set(names); ... nameSet.has(value)); - 错误优先级:.test() 会与 .required() 共同生效;若希望“空值不触发数组校验”,可将 .test() 放在 .required() 之后,并在 test 回调中显式跳过空值(如 if (!value) return true;)。
完整整合后,当用户输入 Tom 并提交,表单将显示 must be in names array! 错误;输入 John 则通过校验并正常提交。该方案简洁、可复用,且完全兼容 @hookform/resolvers/yup 的集成流程。

















