Anthony

Simple Vue.js Form Validation

Simple Vue.js Form Validation

I bet you’d agree with me that client side form validation is not the safest way to handle users inputs or preventing malicious act. However, you can give better feedback to the average user. The user doesn’t have to wait for the page to reload just so it could pop error messages that the email, password or credentials weren’t properly formated (a bad user experience I would say). With client side validation, on the fly we can prevent users from submitting empty field(s), show the strenght of their password, give notice of what characters could be included and which shouldn’t etc.

In Vue.js there are several packages you could install for simple or advanced form validation, vee-validate which is one of the most popular. However in the article our primary focus will be validating inputs by hand in Vue.js.

Setup

A basic form like this, three input fields, we’ll make two required.

 <form @submit.prevent="submit" method="post" action="ServerUrl">
   <label for="name">Name</label>
   <input type="text" name="name" v-model="name">

    <label for="email">Email</label>
   <input type="email" name="email" v-model="email">

      <label for="address">Home Adress(optional)</label>
   <input type="text" name="address" v-model="address">

   <input type="submit" value="Submit">
 </form>

Let’s start from the top. The form has a @submit eventlistener, the .prevent is equivalent to the preventDefault() method in Javascript, we’re basically preventing the default behaviour of the form.

With the v-model directive we’ll be able to check the inputs if they’re empty or not.

Define the properties and an empty array of error

  data(){
    return{
      errors: [],
      name: '',
      email: '',
      address: ''
    }
  }

Before we starting with the validation let’s setup where to display the errors if any of the two required fields are left blank.

At the top of your form.

<p v-if="errors.length">
    Required:
  <ul v-for="(error, index) in errors" :key="index">
    <li>   {{error}}  </li>
  </ul>
</p>

With that done we can now proceed with our validation.

  methods:{
    submit(){
      if(this.name && this.email){
        return true
      }
      this.errors = []
      if(!this.name){
        this.errors.push('First Name')
      }
      if(!this.email){
        this.errors.push('Email Address')
      }
      
    }
  }

Other Alternatives

This article only covers the basic form validation that could be done by hand, like I mentioned previously there are other great libraries that can handle alot of this for you, and here are the ones I would recommend.

Vector Image by Freepik

comments powered by Disqus