Conditional Validation

This page unveils conditional validation in @nattyjs/tidy forms, validation rules adapt to user input for a flexible experience.

This page explores conditional validation techniques in forms using @nattyjs/tidy. Conditional validation allows you to dynamically adjust validation rules based on the user's input or form state, leading to more flexible and user-friendly forms.

Understanding Conditional Validation

Here, we'll demonstrate how to make the "License Number" field mandatory only if the user's age is above 18.

Implementing Conditional Validation

Here's how to implement conditional validation for the license number field in your form:

1. Define the Form Model:

Start by defining the model structure representing the data you want to collect:

const user = {
  age: '',
  licenseNumber: '',
};

2. Create the Form with Conditional Validation

Use useForm to create the form object and define validation rules. Here, we'll use a conditional validator for the licenseNumber field:

import { useForm, Validators } from "@nattyjs/tidy";

const userForm = useForm(user, {
  validators: {
    age: [Validators.required()],
    licenseNumber: Validators.required({
      conditionalExpression: (t) => t.age > 18, // Validate only if age is greater than 18
    }),
  },
});
  • We define a custom validation rule for the licenseNumber field using Validators.required with a configuration object.
  • The conditionalExpression property specifies a function that receives the current form values (t).
  • Inside the function, we check if t.age (user's age) is greater than 18.
  • If the condition is true, the Validators.required validation is applied, enforcing a required license number.
  • If the condition is false (age is less than or equal to 18), the validation is skipped, allowing an empty license number.

3. Write HTML for Conditional Input Controls

Integrate the form object into your template:

<template>
  <div>
    <label for="age">Age:</label>
    <input type="number" id="age" v-model="userForm.age" />

    <label for="licenseNumber">License Number (if over 18):</label>
    <input type="text" id="licenseNumber" v-model="userForm.licenseNumber" />
    <span>{{ userForm.licenseNumber.errorMessage }}</span>
  </div>
</template>
  • We use separate input fields for age and licenseNumber.
  • The licenseNumber field has a label indicating it's required only for users above 18.
  • The errorMessage property of the licenseNumber control displays validation messages.