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.
Here, we'll demonstrate how to make the "License Number" field mandatory only if the user's age is above 18.
Here's how to implement conditional validation for the license number field in your form:
Start by defining the model structure representing the data you want to collect:
const user = {
age: '',
licenseNumber: '',
};
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
}),
},
});
licenseNumber field using Validators.required with a configuration object.conditionalExpression property specifies a function that receives the current form values (t).t.age (user's age) is greater than 18.Validators.required validation is applied, enforcing a required license number.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>
age and licenseNumber.licenseNumber field has a label indicating it's required only for users above 18.errorMessage property of the licenseNumber control displays validation messages.