Yup Validation Using Conditional Rules Based on Dynamic Data Array

Viewed 256

I have an array of data that looks like this:

{
    "fields": [
        {
            "id": 1,
            "name": "My Field 1",
            "type": "textbox",
            "isRequired": true
        },
        {
            "id": 2,
            "name": "My Field 2",
            "type": "email",
            "isRequired": true
        },
        {
            "id": 3,
            "name": "My Field 3",
            "type": "select",
            "options": [
                {
                    "name": "One",
                    "value": 1
                },
                {
                    "name": "Two",
                    "value": 2
                },
                {
                    "name": "Three",
                    "value": 3
                }
            ],
            "isRequired": false
        },
        {
            "id": 4,
            "name": "My Field 4",
            "type": "number",
            "isRequired": false,
            "min": 3,
            "max": 10
        },,
        {
            "id": 5,
            "name": "My Field 5",
            "type": "checkbox",
            "isRequired": false
        },
    ]
}

How do I shape my validation so that each field in the dynamic array is using the validation rules defined in the dynamic fields array?

  • If the field has type: "email" then I need to use .email()
  • If the field has type: "number" then I need to use the .number() and .min().max() from the min/max properties - otherwise, use .string()
  • If the field has isRequired: true then I need to use .required()
const validationSchema = Yup.object()
                            .shape({
                                fields: Yup.array()
                                    .of(
                                        Yup.object()
                                            .shape({
                                                
                                            }),
                                    )
                            })

The final pseudo HTML output should be:

<form>
  <input type="text" name="My Field 1" /> <!-- checks for required value -->
  <input type="text" name="My Field 2" /> <!-- checks for required value and valid email -->
  <select name="My Field 3">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>
  <input type="text" name="My Field 4" /> <!-- checks valid # and min 3 and max 10 -->
  <input type="checkbox" name="My Field 5" />
</form>
0 Answers
Related