Validation
Joi is a powerful schema validation library that helps enforce rules on user input. In a Nuxt 3 application, Joi can be used to validate form data before submission, ensuring data integrity and preventing incorrect or malicious input.
Installation
# To use Joi in your Nuxt 3 project, install it via npm or yarn:
npm install joi
# or
yarn add joi
Using the Validation Schema in a Component
In your Nuxt 3 component, you can use the validation schema to validate form data.
<template>
<form @submit.prevent="onSubmit">
<div class="mb-6">
<FormText
label="Username"
required
v-model="Username"
placeholder="Enter Username"
type="text"
@input="validateField('Username')"
></FormText>
<span v-if="errors.username" class="text-danger-300 pt-8 text-xs">
{{ errors.username }}
</span>
/>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Joi from "joi";
const userName = ref("");
const errors = ref([]);
const isFormValid = computed(() => {
return userName.value && !errors.value.userName;
});
const validationSchema = {
userName: Joi.string().required().messages({
"string.empty": "Username is required",
"any.required": "Username is required.",
}),
};
const validateField = (field) => {
const value = {
userName: userName.value,
}[field];
const { error } = validationSchema[field].validate(value);
if (error) {
errors.value[field] = error.details[0].message;
} else {
delete errors.value[field];
}
};
const onSubmit = async () => {
Object.keys(validationSchema).forEach((field) => validateField(field));
if (isFormValid.value) {
// await apiCall();
}
};
</script>
Explanation
Using Joi for Validation: The validationSchema object defines the validation rules using Joi. Each field is validated with specific rules, such as required().
Reactive Variables: userName holds the form input value, while errors stores validation error messages.
Validation on Input: The validateField function checks for errors when a user types in the field.
Form Submission: The onSubmit function ensures all fields are validated before allowing form submission.
Computed Property for Form Validity: isFormValid checks whether the form is ready for submission by ensuring there are no validation errors.
Conclusion
By following this guide, you can implement form validation in your Nuxt 3 application using the Joi validation library. This ensures that your form data is validated before submission, providing a better user experience and reducing errors.