Form Validation in Vue 3 Using Vee-Validate 4: Range and Confirmation
Written on
Form validation plays a crucial role in any application.
In this article, we will explore how to incorporate Vee-Validate 4 into a Vue 3 application for effective form validation.
Range Validation
The between rule is utilized to ensure that the input number falls within a specified range.
To implement this, you can write:
<template>
<Form @submit="submit" v-slot="{ errors }">
<Field name="field" rules="between:1,10" />
<span>{{ errors.field }}</span>
</Form>
</template>
<script>
import { Form, Field, defineRule } from "vee-validate";
import * as rules from "@vee-validate/rules";
Object.keys(rules).forEach((rule) => {
defineRule(rule, rules[rule]);});
export default {
components: {
Form,
Field,
},
methods: {
onSubmit(values) {
alert(JSON.stringify(values, null, 2));},
},
};
</script>
The rules property accepts a string to apply the validation rule to the Field component.
Additionally, you can pass an object to the rules property for the same purpose:
<template>
<Form @submit="submit" v-slot="{ errors }">
<Field name="field" :rules="validations" />
<span>{{ errors.field }}</span>
</Form>
</template>
The minimum and maximum values for the range are specified in an array, and both values are mandatory.
Confirmation Validation
The confirmed rule checks if the value entered matches that of another field.
To utilize this, you can write:
<template>
<Form @submit="submit" v-slot="{ errors }">
<Field name="password" type="password" />
<Field name="confirmation" type="password" rules="confirmed:@password" />
<span>{{ errors.confirmation }}</span>
</Form>
</template>
The rules property is set to confirmed:@password, ensuring that the confirmation field matches the password field.
All Field components must reside within a Form component.
Digit Validation
The digits rule ensures that the input is numeric and contains a specified number of digits.
For example, you can write:
<template>
<Form @submit="submit" v-slot="{ errors }">
<Field name="field" rules="digits:3" />
<span>{{ errors.field }}</span>
</Form>
</template>
We validate that the input has precisely 3 digits using the string 'digits:3'.
You can also write:
<template>
<Form @submit="submit" v-slot="{ errors }">
<Field name="field" :rules="validations" />
<span>{{ errors.field }}</span>
</Form>
</template>
Conclusion
Using Vee-Validate 4, we can effortlessly implement various form validation rules in our Vue 3 applications.
More content at **plainenglish.io**