This page explores cross-field validation in forms. Cross-field validation allows you to validate form fields based on the values of other fields within the same form, ensuring data consistency and integrity.
Imagine a password confirmation field in a registration form. Cross-field validation ensures that the confirmation password matches the original password entered by the user. This is a common example where the validity of one field depends on another.
Here's a breakdown of implementing cross-field validation for password confirmation using the built-in compare validator from @nattyjs/tidy
Start by defining the model structure for your form data:
const user = {
password: "",
confirmPassword: "",
};
Use useForm to create the form object and define validation rules. Here, we'll use the compare validator for the confirmPassword field:
import { useForm, Validators } from "@nattyjs/tidy";
const userForm = useForm(user, {
validators: {
password: Validators.required(),
confirmPassword: Validators.compare({
fieldName: 'password' // Specify the field to compare against
}),
},
});
useForm function with an object containing validators.confirmPassword field, we use the Validators.compare validator.compare validator configuration, we specify the fieldName property as password. This indicates that the confirmPassword value should be compared against the value of the password field.Integrate the form object into your template:
<template>
<div>
<input type="password" v-model="userForm.password" />
<input type="password" v-model="userForm.confirmPassword" />
<span>{{ userForm.errorMessage.confirmPassword }}</span>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import { useForm, Validators } from '@nattyjs/tidy'
const user = {
password: "",
confirmPassword: "",
};
const userForm = reactive( useForm(user, {
validators: {
password: Validators.required(),
confirmPassword: Validators.compare({
fieldName: 'password' // Specify the field to compare against
}),
},
}))
</script>
<template>
<div>
<input type="password" v-model="userForm.password" />
<input type="password" v-model="userForm.confirmPassword" />
<span>{{ userForm.errorMessage.confirmPassword }}</span>
</div>
</template>