Yup中test()校验新旧密码时即使值不相等也返回错误如何解决
问题根因
- test回调参数用法错误:
.test()方法的校验回调第一个入参是当前被校验的new_password字段值,第二个入参是校验上下文对象,你之前的写法把两个参数含义完全搞错,永远不会得到预期的相等判断结果,因此始终触发报错。 - 校验逻辑写反:Yup的
.test()规则是回调返回true代表校验通过,返回false代表校验失败触发错误提示。你的需求是「新旧密码相等时报错」,因此相等时要返回false,不等时返回true,和你之前写的判断逻辑完全相反。 - 上下文获取错误:如果要在test中取同层级的其他字段值,要么用普通函数通过
this.parent取,要么通过第二个上下文参数的parent属性取,不能直接在入参里获取其他字段值。
修正方案
方案1:保留自定义test的写法
如果你要保留自定义test的实现,修正后的代码如下:
const ProfileEditSchema = t => Yup.object().shape({ password: Yup.string() .notRequired(t('TR_PASSWORD_REQUIRED')) .matches( /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/, t('TR_PASSWORD_HELPER') ), new_password: Yup.string().when('password', { is: password => password != undefined, then: Yup.string() .required(t('TR_PASSWORD_REQUIRED')) .matches( /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/, t('TR_PASSWORD_HELPER') ) .test( 'password-not-equal', 'new and old password are the same', (newPassword, ctx) => { const oldPassword = ctx.parent.password; // 新旧不等返回true(通过),相等返回false(报错) return newPassword !== oldPassword; } ) }) });
方案2:更简洁的最优实现
这种字段值对比的场景不需要自定义test,用Yup内置的ref + notOneOf方法更简洁,性能和可读性都更好:
const ProfileEditSchema = t => Yup.object().shape({ password: Yup.string() .notRequired(t('TR_PASSWORD_REQUIRED')) .matches( /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/, t('TR_PASSWORD_HELPER') ), new_password: Yup.string().when('password', { is: password => password != undefined, then: Yup.string() .required(t('TR_PASSWORD_REQUIRED')) .matches( /^(?=.*[A-Za-z])(?=.*\d)[0-9a-zA-Z!@#$%-.()_']{8,}$/, t('TR_PASSWORD_HELPER') ) // 直接指定不能和password字段值相等,第二个参数为报错提示 .notOneOf([Yup.ref('password')], 'new and old password are the same') }) });
内容的提问来源于stack exchange,提问作者pepinillo6969
相关产品推荐
相关产品推荐

