const validationSchema = Yup.object().shape({
newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});
如果newPassword字段不为空,我只想进行验证检查。 我该怎么做?
const validationSchema = Yup.object().shape({
newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});
如果newPassword字段不为空,我只想进行验证检查。 我该怎么做?
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-check',
'Password must be at least 8 characters',
password => password.length == 0
});
使用"when"方法不再起作用,因为它存在循环依赖关系[从评论部分复制]
const validationSchema = Yup.object().shape({
newPassword: Yup.string().when('newPassword',{
is:(password) => password.length > 0
then: Yup.string().min(8, 'Password must be at least 8 characters');
});
使用 测试 的替代方案:
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-or-8-characters-check',
'Password must be at least 8 characters',
password => !password || password.length >= 8,
),
});
使用 trim()
函数的另一种方法
const validationSchema = Yup.object().shape({
newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
});
const validationSchema = Yup.object().shape({
newPassword: Yup
.string()
.nullable()
.transform((v, o) => (o === '' ? null : v))
.min(8, 'Password must be at least 8 characters')
});
使用.when()
的一种方法,不会像被接受的答案那样产生循环依赖。 .shape()
接受一个详尽的依赖列表作为最后一个参数,以解决循环冲突问题,秘诀是使用相同的key两次 https://github.com/jquense/yup/issues/176#issuecomment-369925782 。
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-or-8-characters-check',
'Password must be at least 8 characters',
password => !password || password.length >= 8,
),
}, [["newPassword","newPassword"]]);
noSortEdges
的任何内容:https://github.com/jquense/yup#objectshapefields-object-nosortedges-arraystring-string-schema 看起来这里有一个关于文档的未解决问题:https://github.com/jquense/yup/issues/1339 - CTS_AEconst validationSchema = Yup.object().shape({
newPassword: Yup
.string()
.matches(/^\w{8}/, "Password must be at least 8 characters")
});
不允许有8个空字符的替代方案。
const notEmpty = Yup.string()
.ensure() // Transforms undefined and null values to an empty string.
.test('Only Empty?', 'Cannot be only empty characters', (value) => {
const isValid = value.split(' ').join('').length !== 0;
return isValid;
});
const validationSchema = Yup.object({
newPassword: notEmpty.min(8, 'Password must be at least 8 characters');
});
我使用了Yup函数nullable()
,因此只有在它不为空时才会通过下一个函数进行验证:
kmBegin: Yup.number().nullable().positive().integer(),
parcelTotal: Yup.number().positive().integer(),
timeBegin: Yup.date(),
timeEnd: Yup.date().nullable(),
.test
。您将在那里访问到原始值。 - undefined