是的验证检查是否为空

Yup validation check if not empty

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});

我只想在新密码字段不为空时进行验证检查。 我该怎么办?

解决这个问题有不同的方法。

使用测试

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().test(
        'empty-check',
        'Password must be at least 8 characters',
         password => password.length == 0
    });

时使用
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,
    ),
});

我使用了 Yup 函数 nullable() 所以只有在它不为 null 时才用下一个函数验证它:

kmBegin: Yup.number().nullable().positive().integer(),
parcelTotal: Yup.number().positive().integer(),
timeBegin: Yup.date(),
timeEnd: Yup.date().nullable(),

有一种方法可以使用 .when() 并且不会像接受的答案那样生成循环依赖,.shape() 接受一个详尽的依赖列表作为最后一个参数,这解决了循环冲突,秘密两次使用相同的密钥 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"]]);

替代使用trim()

const validationSchema = Yup.object().shape({
    newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
  });

我自己解决这个问题的方法是先添加 .nullable(),然后添加 .transform() 空字符串为 null。

const validationSchema = Yup.object().shape({
    newPassword: Yup
        .string()
        .nullable()
        .transform((v, o) => (o === '' ? null : v))
        .min(8, 'Password must be at least 8 characters')
});

最简单的方法是:

const 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');
});