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.
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.
Here's a breakdown of implementing custom validation for username uniqueness.
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;
};
}
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' })] })],
},
});
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>
<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>