I have 2 fields in my form say carriercode and billnum, here I need to validate number should always have value of carriercode as a prefix, ex if carriercode=ABCD blnum should be ABCD followed by any charter can be string or number.
return Yup.object({
carriercode: Yup.string().required(requiredMessage).min(4,"length should be 4").matches(/^[a-zA-Z0-9-]+$/,"Can not contain special characters like ),(,@ etc."),
blnum: Yup.string().required(requiredMessage) //validate if blnum starts with carriercode
})
}
is there any way to achieve this using yup validations, to be simple I need something like startsWith/indexOf functionality in yup.
The test
method can be one of those. Inside test
method, you can access other fields(here carriercode
) by using this.parent['carriercode']
. Just make a custom validator like this:
Yup.object({
carriercode: Yup.string().required(requiredMessage).min(4, "length should be 4").matches(/^[a-zA-Z0-9-]+$/, "Can not contain special characters like ),(,@ etc."),
blnum: Yup.string()
.required("Should be the prefix of carriercode") //validate if blnum starts with carriercode
.test("Check prefix", function () {
let carriercode = this.parent["carriercode"];
let blnum = this.parent["blnum"];
// console.log(carriercode, blnum);
if (carriercode && blnum) {
return blnum.startsWith(carriercode) ? true : false;
}
})
})
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