This page explores asynchronous validation in forms. Asynchronous validation allows you to perform validation checks that involve external data sources or remote API calls, providing real-time feedback to the user.
Imagine a username registration form. In a standard validation approach, the username is checked for emptiness upon submission. However, with asynchronous validation, you can check for username uniqueness against a server database while the user types. This provides instant feedback and improves the user experience.
Start by defining the model structure for your form data:
const user = {
userName: '',
};
Use useForm to create the form object and define a custom function for asynchronous checks:
import { useForm, Validators } from '@nattyjs/tidy';
const userForm = useForm(user, {
validators: {
userName: [Validators.required()],
},
});
Here's the implementation of the uniqueUserName function:
function uniqueUserName() {
return new Promise((resolve, reject) => {
if (userForm.userName === "Bharat") {
userForm.setServerErrors({ userName: 'Username already exists.' });
reject(); // Optional: Explicitly reject the promise for chaining purposes
} else {
userForm.clearErrorMessage('userName');
resolve(); // Optional: Explicitly resolve the promise for chaining purposes
}
});
}
userForm.userName) matches a predefined value ("Bharat").
userForm.setServerErrors and optionally reject the Promise.userName field using userForm.clearErrorMessage and optionally resolve the Promise.In your template, bind the userName field to the form object and call the uniqueUserName function on each user input:
<template>
<div>
<input type="text" @input="uniqueUserName" v-model="userForm.userName" />
<span>{{ userForm.errorMessage.userName }}</span>
</div>
<template>
<script setup lang="ts">
import { useForm, Validators } from '@nattyjs/tidy';
import { reactive } from 'vue';
const user = {
userName:''
};
const userForm = reactive(useForm(user, {
validators: {
userName:[Validators.required()]
},
}))
function uniqueUserName() {
return new Promise(()=>{
if(user.userName == "Bharat")
userForm.setServerErrors({userName:'Username already exists.'})
else
userForm.clearErrorMessage('userName')
})
}
</script>
<template>
<div>
<input type="text" @input="uniqueUserName" v-model="userForm.userName" />
<span>{{ userForm.errorMessage.userName }}</span>
</div>
</template>