Cross Field Validation (Compare Password)

This page explains cross-field validation, ensuring form data consistency by checking fields against each other.

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.

Understanding Cross-Field Validation

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.

Implementing Cross-Field Validation

Here's a breakdown of implementing cross-field validation for password confirmation using the built-in compare validator from @nattyjs/tidy

1. Define the Form Model:

Start by defining the model structure for your form data:

const user = {
  password: "",
  confirmPassword: "",
};

2. Create the Form

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
    }),
  },
});
  • We define validation rules using the useForm function with an object containing validators.
  • For the confirmPassword field, we use the Validators.compare validator.
  • Inside the 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.

3. Write HTML for Input Controls

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>

Complete Code Walkthrough

<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>