Vue js is growing rapidly. The increasing list of great features and performance makes it one of the best JavaScript frameworks. It has a smaller learning curve too that makes it a great choice for building UX(User Experience). In this article, we will learn vue js form validation. We will use bootstrap to make things look pretty.

Vue js form validation

First of all, if you are new to Vue I would suggest you check Vue js tutorial. It will help you to get started with Vue js. However, if you are a React or Angular developer then I would suggest you have a look at Vue js advantages.

We will use npm as Vue CLI provides a great way to play with it. So open up the command prompt and go to your desired directory. Now create a new vue js project there by using the following command.

vue init webpack form-validation

Creating the template

Once the folder has been created open it from your favorite text editor. You will find a folder called src within the root directory of your project. Go inside of it and there will be a folder called components.

There will be a predefined component, we don’t need it so you can safely remove it. Now create a new component called Home.vue in the same directory. Now inside of the template tags create a form.

I am using Bootstrap 4 and its predefined classes to make things easier. You can install it directly using npm and import it within your main.js file.

<form @submit.prevent="validate">
	<div class="form-group">
		<input type="text" class="form-control" id="name" placeholder="Your name">
	</div>
	<div class="form-group">
		<input type="text" class="form-control" id="email" placeholder="Your email">
	</div>
	<div class="form-group">
		<textarea class="form-control" id="comment" placeholder="Your comment"></textarea>
	</div>
	<button class="btn btn-primary" type="submit">Validate</button>
</form>

I have added markup for a simple comment form with 3 required fields. I guess there’s nothing extraordinary just few bootstrap classes. So let’s move to the main part.

Bootstrap provides an is-invalid class that helps in showing field with the error. So we will need to add this class when the field is invalid.

Vue provides a great way to bind classes with data variables. Let’s see how we can use it.

<input type="text" class="form-control" v-bind:class="{ 'is-invalid': nameError }" id="name" placeholder="Your name">

Suppose we have a nameError variable within data. If the variable is true the is-invalid class will be added to the field automatically. Now you can add v-bind property to other fields with emailError and commentError variables.

We have almost completed the template part but. Have not we missed something?

Yeah, we haven’t added something to display the error message. Let’s handle it in the next section.

Adding the required variables

<script>
	export default {
		name: 'home',
		data() {
			return {
				nameError: false,
				emailError: false,
				commentError: false,
			}
		}
	}
</script>

Inside of the script, we have added 3 boolean variables. Initially, they are set to false so that invalid class will not be added before validation. Now let’s move to methods section and define our validate method.

Ohh ups we have missed something again!. We need to deal with the user input. The two-way data binding of Vue makes it really easy to manipulate user inputs. So let’s add few more variables inside return.

name: '',
email: '',
comment: '',

Now in order to bind this to our inputs, we will need to use the v-model directive as follows.

<input type="text" class="form-control" v-bind:class="{ 'is-invalid': nameError }" id="name" placeholder="Your name" v-model="name">

Finally, do the same with the rest of the fields. So we can now manipulate inputs and define our validate method logic.

However, you may notice we have not thought of error messages yet. Generally, you can handle this in many different ways. I will explain the easier one. Let’s add an errors array inside return as follows.

errors: []

We have done the base part now let’s move to the validation part and define our logic in the next section.

Defining the validation logic

Extend the script and add the method as follows.

methods: {
	validate() {
		
	}
}

The structure is ready so let’s start with name validation. Suppose we want the name to be between 5 to 20 characters. Then we can add the following validation logic.

var len = this.name.length;
if (len < 5 || len > 20) {
	this.nameError = true;
	this.errors.push({
		'message': 'Name must be between 5 to 20 characters long.'
	});
}

In the above code, we have added a condition that will execute on validation fail. Notice that I have added the message as a string you can use an array if it will contain more than one error messages. You can create your own simple validation rules like this one. I hope you will create rest of the field’s validation by yourself. However, I have added an embedded code below you can use that for reference.

Now we have added a message to the validation error. So let’s add markup to display it inside of our template as follows.

<div class="invalid-feedback" id="feedback-1" v-if="errors[0]">
	{{ errors[0].message }}
</div>

The bootstrap invalid-feedback class provides a good way to display error messages. As the name is our first field so in order to display the error message of the name we will need to fetch index 0 of errors array.

Initially, the errors array is empty so a v-if directive is added to display the vue js form validation message if index 0 exists. You can follows this same procedure to display the error message for other fields too.

Extending the features

First of all, imagine what will happen if you try to validate more than once. The previous error messages are still in the errors array right!.

So in order to solve this issue, you can simply set errors array to empty at the first line of our validate method.

this.errors = [];

Now, what if a field is validated and other fields have errors!. We must specify what will happen if the field is validated and has no errors.

We can do this with a simple else statement as follows.

else {
	document.getElementById('name').className = "form-control is-valid";
	this.errors.push({
		'message': 'Validated.'
	});
	document.getElementById('feedback-1').className = "valid-feedback";
}

If the field is valid we are removing the previous classes and adding 2 classes. This will help you to get rid of overlapping classes. At the last line, we have changed the class of error message block to valid-feedback.

You will be able to see the following output once its ready.

Finally, its ready to play with. Hope you have liked this vue js form validation article. However, if I have missed anything let me know by commenting below.


Subham Mitra

A coder who loves to solve real-world problems through coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.