Last Updated On By Anmol Lohana
The browser supports form validation natively, but sometimes different browsers will handle things that make it tricky to rely on them. Even if the validation is supported perfectly, sometimes there is the need for custom validations and more manual. In this article, we will do form validation in vue.js.
The form contains different fields. To monitor or control the input that users enter into the form fields, you should conduct both client and server-side validation for quality assurance.
Vue.js enables developers to create forms in Vue applications just as they would with HTML5. It means little to no additional skills are required to build forms in the Vue template section of any component with plain HTML.
Let’s see the process of creating form validation in vue.js
Table of Contents
There are some requirements to perform this task.
node -v
npm install –g @vue/CLI
Create a project and inside the project directory
npm install vuelidate
Let’s set up our project.
import Vue from "vue";
import App from "./App.vue";
import Vuelidate from "vuelidate";
Vue.use(Vuelidate);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
<template>
<div id="app">
<main class="formContain">
<section>
<label for="fname">Name*</label>
<input id="fname" v-model="$v.formResponses.name.$model" type="text">
<p v-if="errors" class="error">
<span v-if="!$v.formResponses.name.required">this field is required.</span>
<span
v-if="!$v.formResponses.name.minLength"
>Field must have at least {{ $v.formResponses.name.$params.minLength.min }} characters.</span>
</p>
</section>
<section>
<label for="femail">Email*</label>
<input id="femail" v-model="$v.formResponses.email.$model" type="email">
<p v-if="errors" class="error">
<span v-if="!$v.formResponses.email.required">this field is required.</span>
<span v-if="!$v.formResponses.email.email">Needs to be a valid email.</span>
</p>
</section>
<section>
<label for="fpass1">Password*</label>
<input id="fpass1" v-model="$v.formResponses.password1.$model" type="password">
<p v-if="errors" class="error">
<span v-if="!$v.formResponses.password1.required">this field is required.</span>
<span
v-if="!$v.formResponses.password1.strongPassword"
>Strong passwords need to have a letter, a number, a special character, and be more than 8 characters long.</span>
</p>
</section>
<section>
<label for="fpass2">Please re-type your Password</label>
<input id="fpass2" v-model="$v.formResponses.password2.$model" type="password">
<p v-if="errors" class="error">
<span v-if="!$v.formResponses.password2.required">this field is required.</span>
<span v-if="!$v.formResponses.password2.sameAsPassword">The passwords do not match.</span>
</p>
</section>
<section>
<button @click.prevent="submitForm" class="submit">Submit</button>
<p v-if="errors" class="error">The form above has errors,
<br>please get your act together and resubmit
</p>
<p v-else-if="empty && uiState === 'submit clicked'" class="error">The form above is empty,
<br>cmon y'all you can't submit an empty form!
</p>
<p v-else-if="uiState === 'form submitted'" class="success">Hooray! Your form was submitted!</p>
</section>
</main>
</div>
</template>
<script>
import { required, minLength, email, sameAs } from "vuelidate/lib/validators";
export default {
data() {
return {
uiState: "submit not clicked",
errors: false,
empty: true,
formResponses: {
name: null,
email: null,
password1: null,
password2: null
}
};
},
validations: {
formResponses: {
name: {
required,
minLength: minLength(2)
},
email: {
required,
email
},
password1: {
required,
strongPassword(password1) {
return (
/[a-z]/.test(password1) && //checks for a-z
/[0-9]/.test(password1) && //checks for 0-9
/\W|_/.test(password1) && //checks for special char
password1.length >= 8
);
}
},
password2: {
required,
sameAsPassword: sameAs("password1")
}
}
},
methods: {
submitForm() {
this.empty = !this.$v.formResponses.$anyDirty;
this.errors = this.$v.formResponses.$anyError;
this.uiState = "submit clicked";
if (this.errors === false && this.empty === false) {
//this is where you send the responses
this.uiState = "form submitted";
}
}
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
label {
margin: 20px 0 10px;
display: block;
}
.error {
text-transform: uppercase;
font-size: 12px;
color: red;
position: absolute;
}
.success {
text-transform: uppercase;
font-size: 12px;
color: teal;
position: absolute;
}
.formContain section {
padding-bottom: 30px;
position: relative;
}
</style>
Inside the main.js file, you need to import the Vue module, app.vue to access the file’s code and vuelidate for validation.
Then inside the app.vue file, we added a template tag inside, we created a form add input fields, labels, button, and the required fields for the form. And we added a script tag inside, which we added the conditions to validate each field. And then, finally, we added a style tag to give styling to the form.
Let’s see the output and check the validation conditions by not filling the form inputs and see the result.
In the above-given snapshot, we can see that it’s showing a “This field is required” error when we didn’t provide a name inside the name field.
In the email field, we didn’t enter the email’s correct format, so it’s showing the “Needs to be a valid email” error because we need to enter the correct email.
The user needs to enter a strong password else; anyone can guess it easily; that’s why it’s required to provide a strong password.
The password must contain characters, numbers, and special characters and must be more than eight characters.
Both password fields must contain the same input; else, it will show the mismatch error.
In all conditions above, we saw the form is not submitted because some states are not meeting. Let’s observe the behavior of the form on providing all correct inputs.
Here we go! All the fields contain valid data, and our form is submitted successfully.
In this article, we saw the whole process of validating the form in vue.js. We mentioned all the requirements and created the project of form validation. Then we visited different validation conditions where it was showing error messages (validation errors ). And we saw how to get rid of those error messages according to validation rules.