This documentation serves as a guide for using form validation functionalities within your application. We'll explore various validation scenarios, starting with creating a simple form and gradually progressing towards more complex validations.
Imagine you're building a registration form where users need to provide basic information, such as name, email, and age. You want to ensure users enter valid data in the respective fields before submitting the form.
Here's how to create a simple registration form with basic validation:
Start by defining a model to represent the data you want to collect from the user. This model will typically be a plain JavaScript object with properties corresponding to each form field.
const user = {
name: "",
email: "",
age: 0,
};
First, we import the useForm composition API for creating the form object. We simply need to pass the defined JavaScript object and set the validation rules. Here's the code example:
import { useForm } from "@nattyjs/tidy";
const userFrom = useForm(user, {
validators: {
name: Validators.required(),
email: [Validators.required(), Validators.email()],
age: [Validators.required(), Validators.numeric()],
},
});
Once the form object is created, we can use it within the respective input controls. Here's an example using Vue syntax (adapt it to your specific framework):
<template>
<div>
<input type="text" v-model="userFrom.name" />
<input type="text" v-model="userFrom.email" />
<input type="text" v-model="userFrom.age" />
</div>
</template>
We've assigned validators to the respective fields. To show error messages on the UI, we can use the errorMessage property within the form object. This property is a string that displays the specific validation error message, if the error message is configured at global level or individual level. Here's an example you can use and adapt to your framework:
<span>{{ userForm.errorMessage.name }}</span>
The submit button should only be enabled when the form is valid according to the bound validators on each input control. Here's the code to enable the submit button only when the form is valid (adapt the syntax to your framework):
<button :disabled="!userForm.valid">Submit</button>
<script setup lang="ts">
import { reactive } from 'vue';
import { useForm, Validators } from '@nattyjs/tidy';
const user = {
name: '',
email: '',
age: 0,
};
const userForm = reactive(
useForm(user, {
validators: {
name: Validators.required(),
email: [Validators.required()],
age: [Validators.required()],
},
})
);
</script>
<template>
<div>
<input v-model="userForm.name" type="text" />
<span>{{ userForm.errorMessage.name }}</span>
<input v-model="userForm.email" type="text" />
<span>{{ userForm.errorMessage.email }}</span>
<input v-model="userForm.age" type="text" />
<span>{{ userForm.errorMessage.age }}</span>
<button :disabled="!userForm.valid">Submit</button>
</div>
</template>
You can start playing with this template in your browser using our online sandboxes: