Search code examples
vue.jsvuelidate

Check value on a particular array index in Vuelidate


I have the following form array in Vuelidate. But how can I base some validation based on another field's value on the same array index.

Below is my none working example, but I want the forename to be required IF something has been entered for the surname.

validations: {
        fixturesArray: {
            $each: {
                fixtureName: {
                    //required
                },
                guestDetails: {
                    $each: {
                        forename: {
                            required: requiredIf(function() {
                                return $each.surname != ""
                            })
                        },
                        surname: {

                        },
                        dietaryRequirements: {
                            $each: {
                                name: {

                                }

                            }
                        }
                    }
                }
            }
        }
    },

Solution

  • let's assume your case is: Forename is required if surname is not null

    validations: {
        fixturesArray: {
            $each: {
                guestDetails: {
                    $each: {
                        forename: {
                            requiredIf: requiredIf((obj) => obj.surname != null)
                        },
                        surname: {
    
                        }
                    }
                }
            }
        }
    }
    

    You can use requiredIf in $each like that, although this is not stated in the documentation. The obj parameter is the object being validated in this iteration. You can see more information here.

    Hope it helps, cheers.