Reputation: 387
const validationSchema = Yup.object().shape({
newPassword: Yup.string().min(8, 'Password must be at least 8 characters');
});
I want to validation check only if newPassword field is not empty. How could I do?
Upvotes: 26
Views: 81691
Reputation: 2463
You can use test to do this:
const validationSchema = Yup.object().shape({
newPassword: Yup.string().test(
'empty-check',
'Password must be at least 8 characters',
password => password.length == 0
});
Upvotes: 26
Reputation: 26732
Alternative that won't allow 8 empty characters.
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');
});
Upvotes: 1
Reputation: 19
The simplest way is:
const validationSchema = Yup.object().shape({
newPassword: Yup
.string()
.matches(/^\w{8}/, "Password must be at least 8 characters")
});
Upvotes: 0
Reputation: 71
The way I solved this for myself was to first add .nullable() and then .transform() empty string into a 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')
});
Upvotes: 7
Reputation: 875
Alternative using trim()
const validationSchema = Yup.object().shape({
newPassword: Yup.string().trim().required("Password must be at least 8 characters"),
});
Upvotes: 13
Reputation: 41
There is a way of using .when()
and not generating a cyclic dependency like the accepted answer, .shape()
accepts an exhaustive list of dependencies as last argument, that resolves the cyclic conflict, the secret is using the same key twice 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"]]);
Upvotes: 4
Reputation: 229
Alternative using test:
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,
),
});
Upvotes: 13
Reputation: 6302
I used the Yup function nullable()
so it is only validated with the next functions if it not null:
kmBegin: Yup.number().nullable().positive().integer(),
parcelTotal: Yup.number().positive().integer(),
timeBegin: Yup.date(),
timeEnd: Yup.date().nullable(),
Upvotes: 0