Custom Validation

This page empowers you to craft custom validation rules for your forms, going beyond built-in options.

This page explores creating custom validation rules in forms. Custom validation allows you to define specific validation logic beyond built-in validators, enabling more tailored validation scenarios for your application.

Understanding Custom Validation

Imagine a registration form where usernames must be unique. Standard validators might not handle this directly. With custom validation, you can create a validator function to check username uniqueness against your specific criteria.

Implementing Custom Validation

Here's a breakdown of implementing custom validation for username uniqueness.

1. Define the Validation Function

Create a function that encapsulates your custom validation logic:

import { ParamInfo } from "@nattyjs/tidy"

interface UserConfig {
  name:string
}

function uniqueUserValidator(config: UserConfig) {
  return (params: ParamInfo): ValidatorFunc | null => {
    if (params.value === config.name) {
      return {
        unique: { message: 'This field should be unique.' },
      };
    }
    return null;
  };
}

2. Use Custom Validation in Form Definition

Use useForm to create the form object and integrate the custom validator

import { useForm } from '@nattyjs/tidy'

const userForm = useForm(user, {
  validators: {
    userName: [Validators.custom({ validators: [uniqueUserValidator({ name: 'Bharat' })] })],
  },
});

3. Integrate the Form Input

In your template, bind the userName field to the form object

<template>
  <div>
    <input type="text" v-model="userForm.userName" />
    <span>{{ userForm.errorMessage.userName }}</span>
  </div>
</template>

Complete Code Walkthrough

<script setup lang="ts">
import {  useForm, Validators,ParamInfo, ValidatorFunc } from '@nattyjs/tidy';
import { reactive } from 'vue';
interface UserConfig{
  name:string
}
function uniqueUserValidator(config:UserConfig){
  return (params:ParamInfo):ValidatorFunc=>{
    if(params.value == config.name)
      return {
        unique:{message:'This field should be `Bharat`.'}
      }
    return null;
  }
}
const user = {
  userName:''
};

const userForm = reactive(useForm(user, {
  validators: {
    userName:[Validators.custom({validators:[uniqueUserValidator({name:'Bharat'})]})]
  },
}))
</script>

<template>
<div>
  <input type="text" v-model="userForm.userName" />
  <span>{{ userForm.errorMessage.userName }}</span>
</div>
</template>