DEV Community

loading...
Cover image for The easiest way to add native form validation in Vue.js. ✔

The easiest way to add native form validation in Vue.js. ✔

vaibhavkhulbe profile image Vaibhav Khulbe ・5 min read

Now, this statement might be bold but this is what I found out to be the easiest way possible to add some validations natively. Though there are many libraries like FormValidation and Vuelidate, one of the simpler way to check the input elements (and others) is to go the native way which is built into Vue.

Ready to add some checks? Let's get this real quick!

Valid GIF

It doesn't matter if the form is valid or not, what matters is that you're valid! (I made a bad sentence 🤦‍♂️)

What's in the form? 📄

Let's take the simplest of the lot. There are two input fields, one drop-down and one submit button. It doesn't look pretty, and remember, we're here to do the validation.

Here are the different states of our form:

The default state

Default state form

The filled state

Filled State form

The error(s) state

If one of the required fields is not filled...

First error state

If you try to submit without your name/review/ratings...

Second error state


Code it! 👨‍💻

I hope you're good with the HTML and CSS part of the form. If not, you can see the code in the embed towards the end of this article.

The product-review component takes in the following HTML as a template:

<form class="form" @submit.prevent="onSubmit">
        <p>
          <label for="name">Name:</label>
          <input id="name" v-model="name">
        </p>

        <p>
          <label for="review">Review:</label>      
          <textarea id="review" v-model="review"></textarea>
        </p>

        <p>
          <label for="rating">Rating:</label>
          <select id="rating" v-model.number="rating">
            <option>⭐⭐⭐⭐⭐</option>
            <option>⭐⭐⭐⭐</option>
            <option>⭐⭐⭐</option>
            <option>⭐⭐</option>
            <option></option>
          </select>
        </p> 
        <p>
          <input type="submit" value="Submit"> 
        </p>    
    </form>

As you can see, it's a pretty straightforward code having the @submit.prevent event modifier attached to the onSubmit method which we will define later.

We're using the v-model directive on the name input, review text field, and the rating selector to give us two-way data-binding.

Add custom validation

Let's first create the onSubmit method. Here, we make the productReview object which refers to the name, review and rating which should've been initialised inside the data() object as null.

onSubmit() {
    let productReview = {
        name: this.name,
        review: this.review,
        rating: this.rating
    }
    this.name = null
    this.review = null
    this.rating = null
}

To collect the errors, we'll make an empty errors array in our data object of Vue instance.

Next, we use good old if-else in JavaScript to check if there is some data entered in these three fields or not. Hence, we wrap our productReview object inside the if as:

if(this.name && this.review && this.rating) {
    let productReview = {
        name: this.name,
        review: this.review,
        rating: this.rating
    }
    this.name = null
    this.review = null
    this.rating = null
}

Now, if these values are not filled in, we add the else block and check if there is not a name, rating or a review, then simply push() this into our initially empty errors array with the error message we want to display inside the push() function's argument as a String.

else {
    if(!this.name) this.errors.push("Name required.")
    if(!this.review) this.errors.push("Review required.")
    if(!this.rating) this.errors.push("Rating required.")
}

Display those errors

Inside of our template, we add a new <p> tag before the name input field. Using Vue's v-if directive, we'll check if errors array has some length. This means when errors is not empty (i.e it has some errors), we add a <b> which says "Please correct the following error(s):"

<p v-if="errors.length">
    <b>Please correct the following error(s):</b>
    <ul>
        <li v-for="error in errors">{{ error }}</li>
    </ul>
</p>

For a single of multiple errors, we'll display it in an unordered list. Therefore, for each <li>, we use the v-for directive to iterate through the array to print each of the error.

And there you have it! Try submitting the form by leaving on or two (or if you don't even have a name, leave them all! ( ̄︶ ̄)↗). The form should send the error message(s). 🥳

If you're stuck somewhere in the code or just want to see the output, I've embedded the Pen below:


Where to next? 🤔

While this was a super simple beginner-friendly approach towards form validation in Vue, your app may be much more complex or big. For that you can try out the following resources:


Thanks for reading, I appreciate it! Have a good day. (✿◕‿◕✿)



📫 Subscribe to my weekly developer newsletter 📫

PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, here's my Medium profile.

Discussion

pic
Editor guide