I'm working on a ReactJS project. I'm learning to use Yup
for Validation with FormIk
. The following code works fine:
const ValidationSchema = Yup.object().shape({
paymentCardName: Yup.string().required(s.validation.paymentCardName.required),
paymentCardNumber: Yup.string()
/*
.test(
"test-num",
"Requires 16 digits",
(value) => !isEmpty(value) && value.replace(/\s/g, "").length === 16
)
*/
.test(
"test-ctype",
"We do not accept this card type",
(value) => getCardType(value).length > 0
)
.required(),
But the moment I uncomment the test-num
the developer tools complain about an uncaught promise:
How do I get Yup to give me a different error string based on the validation failure that I detect?
You can use the addMethod method to create two custom validation methods like this.
Yup.addMethod(Yup.string, "creditCardType", function (errorMessage) {
return this.test(`test-card-type`, errorMessage, function (value) {
const { path, createError } = this;
return (
getCardType(value).length > 0 ||
createError({ path, message: errorMessage })
);
});
});
Yup.addMethod(Yup.string, "creditCardLength", function (errorMessage) {
return this.test(`test-card-length`, errorMessage, function (value) {
const { path, createError } = this;
return (
(value && value.length === 16) ||
createError({ path, message: errorMessage })
);
});
});
const validationSchema = Yup.object().shape({
creditCard: Yup.string()
.creditCardType("We do not accept this card type")
.creditCardLength('Too short')
.required("Required"),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With