The useForm composition API function from @tidy simplifies form management in your SPA applications. It provides a efficient way to define form state, integrate validation rules, handle form interactions, and access error messages. This streamlines form development, improves code organization, and enhances the developer experience.
Let's create a login page form with a single input element for the userName. We'll implement several validations and enable the submit button only when all validations pass. The validations include:
userName cannot be empty.userName can only contain letters and numbers.userName must be at least 6 characters long.userName cannot exceed 10 characters.Upon validation failure, the corresponding error message will be displayed.
useFormTo create the form object, we use the useForm function and pass it an initial state object with the userName property set to an empty string.
import { useForm } from '@nattyjs/tidy';
const form = useForm({ userName: '' });
Now, let's define the validation rules using the Validators option within useForm:
const form = useForm({ userName: '' }, {
validators: {
userName: [
Validators.required(),
Validators.minLength({ value: 6 }),
Validators.alphaNumeric(),
Validators.maxLength({ value: 10 }),
],
},
});
Validators.required(): Ensures the userName field is not empty.Validators.minLength({ value: 6 }): Sets a minimum length of 6 characters for the userName.Validators.alphaNumeric(): Allows only letters and numbers in the userName.Validators.maxLength({ value: 10 }): Sets a maximum length of 10 characters for the userName.Here's the HTML template for the login form using Vue components:
<script setup lang="ts">
import { reactive } from 'vue';
import { useForm, Validators } from '@nattyjs/tidy';
const form = reactive(
useForm(
{ userName: '' },
{
validators: {
userName: [
Validators.required(),
Validators.minLength({ value: 6 }),
Validators.alphaNumeric(),
Validators.maxLength({ value: 10 }),
],
},
}
)
);
</script>
<template>
<div>
<label for="userName">User Name</label>
<input type="text" id="username" v-model="form.userName" />
<span>{{
form.errorMessage.userName
}}</span>
<button :disabled="!form.valid">Submit</button>
</div>
</template>
You can start playing with this template in your browser using our online sandboxes: