Dynamically add rules to validate

Viewed 667

with vee-validate, a validation lib for Vuejs, supporting reactive validation schema I was thinking about adding validation on dynamic fields.

What I want to archive

I got a dynamic list of fields that I would like to validate. Each field contains information about the input-type (string, boolean, integer, ...) and whether it's required or not.

Example:

computed: {
    schema () {
        let schema = Yup.object ({
            category: Yup.object ().shape ({
                name: Yup.string ().max (255).required ()
            })
        });

        this.fields.forEach((field)=>{
            console.log(field);
        })

        return schema;
    },
},

Inside of the forEach-loop you can see that I am logging the field. The result is:

Proxy {id: 1, name: "example_integer", placeholder: "", type: "integer", required: true, value: null}
Proxy {id: 2, name: "example_string", placeholder: "Type something", type: "string", required: false, value: null}

For this example, the schema should be expanded by two rules:

example_integer: Yup.number().required(),
example_string: Yup.string().nullable()

Now I was wondering which way to prefer:

  1. I could try to add those rules to schema using my forEach-loop
  2. I could try to avoid this additional step and add this logic just inside the initial schema-declaration

I would love to hear which way you'd prefer. If you got information on how to do this most elegantly, I'd love to hear that.

My first attempt:

return Yup.object ({
    category: Yup.object ().shape ({
        name: Yup.string ().max (255).required (),
        fields: Yup.array ().of (
            Yup.object ().shape ({
                value: Yup.lazy (val => {
                console.log (val);
                return Yup.string ();
            })
        ),
    })
});

But unfortunately console.log (val); returns only the value of that object, but in this case I'd need to check the type and required props.

0 Answers
Related