{{announcement.body}}
{{announcement.title}}

Vue Tutorial 6 - Form Validation

DZone 's Guide to

Vue Tutorial 6 - Form Validation

In this article, we discuss how to perform form validation on the client-side with Vue.js in order to ensure quality input from users.

· Web Dev Zone ·
Free Resource

lake-view-benches.

In the previous article, we have implemented a quite impressive Guest Management App with Vue.  V-model was the latest Vue directive we learned, and if you recall, it allowed us to effortlessly bind form input to the app data. 

Granny’s party is just around the corner, and she loves our new app. However, she found an issue. It turns out that even if she doesn’t enter any data into the form, she can still submit it. This then results in an empty row being added to her list of guests. She was deeply disappointed with this discovery. After all, her grandchild is to be a Principal Software Engineer and slip-ups like this are unacceptable. 

In short, we didn’t get around to validating the form input, and that’s what we’ll look at in this tutorial.

You may also like: Everything React: Tutorials for Beginners and Experts Alike.

Form Validation

I presume you’ve done some input validation before, and you don’t need an explanation of why it's required in real-world applications. Naturally, it’s not sufficient to simply validate the input on the client-side (using Vue, React, Angular, etc.). One must also validate it on the server-side. However, this would be outside of the scope of this tutorial. For now, we’ll focus on client-side validation only. 

We will validate the input every time a user attempts to submit. Therefore, it would be fitting to put the validation logic inside the addGuest method. However, instead of doing that, we’ll define another method solely responsible for validation: isValid. 

isValid: function () {
    return false
},


Let’s now call this method inside the addGuest method. 

addGuest: function () {

    if (this.isValid()) {

        console.log(`Adding guest ${this.name} ${this.confirmed} ${this.tableNumber} ${this.allergies}`)
        let guest = {
            name: this.name,
            confirmed: this.confirmed,
            tableNumber: this.tableNumber,
            allergies: this.allergies
        }
        this.guests.push(guest)

        this.name = ''
        this.confirmed = false
        this.tableNumber = ''
        this.allergies = []

    } else {
        console.log("Input failed validation")
    }
}


You can see that we only proceed to add a guest if the isValid method returns true. For now, isValid   always returns false, which means that we will always get the “Input failed validation” log in the console.

Input failed validation

Input failed validation

Let’s fix the isValid method so it returns true or false appropriately. Here are the validation rules we must ensure are enforced:

  • Name is required.
  • Name is longer than 2 chars.
  • Name is no longer than 20 chars.
  • Table number has been set.

There’s no need to validate the RSVP or Dietary Requirements checkboxes, as all of those are optional. I’d like for you to attempt to implement the isValid method by yourself. Once you are done you can compare it to my solution:

isValid: function (name, tableNumber) {
    this.errors = []
    if (name === '') {
        this.errors.push("Name is required")
    } else if (name.length > 20 || name.length <= 2) {
        this.errors.push("Name must be at least 3 chars and at most 20 chars")
    }

    if (tableNumber === '') {
        this.errors.push("Table Number is required")
    }

    if (this.errors.length > 0) {
        return false
    } else {
        return true
    }
},


Now that we have a working validation method implemented, no invalid rows get inserted to the table. Success! However, it's only a partial win. Unfortunately, our current solution is not sufficient because there’s no visual feedback explaining why the form failed validation. Therefore, we must display a list of errors for our users benefit. 

You can achieve this quite simply using the v-if and the v-for directives.  

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


Displaying errors when form input isn&apos;t valid

Displaying errors when form input isn't valid

We could improve this app by implementing inline validation. However, it’s up to you to try implementing this should you wish to do so. Inline validation means that errors would be displayed directly below the relevant field, rather than on top of the entire form. Inline validation is particularly useful for long forms where the user would have to scroll to see the errors. 

Conclusion

In this tutorial, we’ve implemented a simple form validation with Vue. Client-side validation is a feature of every modern website, so the knowledge you gained today will come in handy when you're building your million dollar idea website! 

The code for this tutorial is available here.

Note: You can find parts one, two, three, four, and five of this series at their respective links. 


Further Reading

Topics:
vuejs 2 ,vuejs 2 tutorial ,form validation ,vue form validation

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}