React Yup验证:限制姓名三个字段长度总和不超75字符
Yup实现姓名总长度不超过75字符的验证
要实现firstName、middleName和lastName三者总长度不超过75字符的验证,你可以借助Yup的自定义test方法来实现。以下是修改后的完整验证schema:
const schema = Yup.object().shape({ contacts: Yup.array().of( Yup.object().shape({ names: Yup.array().of( Yup.object().shape({ firstName: Yup.string() .required('First Name is required.') .max(45, 'Only 45 characters allowed.'), middleName: Yup.string(), lastName: Yup.string() .required('Last Name is required.') .max(45, 'Only 45 characters allowed.'), }) // 添加自定义总长度验证 .test( 'name-total-length', 'First, middle, and last name combined must not exceed 75 characters.', (name) => { // 处理字段为空的情况,将undefined转为空字符串 const firstNameLength = (name.firstName || '').length; const middleNameLength = (name.middleName || '').length; const lastNameLength = (name.lastName || '').length; return firstNameLength + middleNameLength + lastNameLength <= 75; } ) ), }) ), });
关键说明:
- 用
.test()方法给每个names数组中的对象添加自定义验证规则:第一个参数是验证的唯一标识,第二个是错误提示文本,第三个是核心验证逻辑函数。 - 验证函数里把可能为
undefined的字段(比如可选的middleName)转为空字符串,避免出现读取length属性的报错。 - 计算三个字段的长度总和,判断是否≤75,返回
true代表验证通过,返回false则触发预设的错误提示。
另外已修正你原始代码中缺失的闭合括号与花括号,确保schema语法合法。
内容的提问来源于stack exchange,提问作者rexroxm
相关产品推荐
相关产品推荐

