Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yup validation to validate form field whether starts with value of other input field

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.

like image 766
Hema Avatar asked Oct 19 '25 03:10

Hema


1 Answers

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;
            }
        })
})
like image 159
Shahnawaz Hossan Avatar answered Oct 21 '25 18:10

Shahnawaz Hossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!