As developers, we tend to get agitated when it comes to form validation. A validation is a set of rules that must be adhered before submitting a form. We'll take a look at how we gracefully handle form errors and a simple form fields validation.

For this simple implementation, we'll use two input fields: firstName and lastName.

Vue Template

<div id="app">
  <form
    @submit="handleFormSubmit"
  >
    <!-- First Name -->
    <label 
      for="firstName"
      :class="{ error: errorsInclude('firstName') }"
    > 
      <span>First Name<em>*</em></span>
      <input
        id="firstName"
        type="text"
        v-model="firstName"
        name="firstName"
        placeholder="First Name"
      />
      <p>
        Please enter your first name
      </p>
    </label>

    <!-- Last Name -->
    <label 
      for="lastName"
      :class="{ error: errorsInclude('lastName') }"
    >
      <span>Last Name<em>*</em></span>
      <input
        id="lastName"
        type="text"
        v-model="lasttName"
        placeholder="Last Name"
      />
      <p>
        Please enter your last name
      </p>
    </label>

    <!-- Submit button -->
    <button>Submit</button>
        
  </form>
</div>

A typical HTML markup you would normally have. Within the <form> tags, we have our form fields and a submit button. We attached a forum submit event handler, handleFormSubmit, which you'll see in a bit. I specifically left out other form attributes: action and method as those are not important to our example. We've went a bit further to add an error class and a function to check for a specific error name, errorsInclude, onto our <label> tags to display a nice little message, to our users, when a validation has failed for a required field.

JavaScript

new Vue({
  el: '#app',
  data: {
    errors: [],
    firstName: null,
    lastName: null
  },
  methods: {
    handleFormSubmit (e) {

      if (this.firstName && this.lastName) {
        // Submit form
        alert("Submitting form...🚀")
        return
        
      }
      
      this.errors = [];

      if (!this.firstName) {
        this.errors.push("firstName");
      }
      
      if (!this.lastName) {
        this.errors.push('lastName');
      }

      e.preventDefault();
    },
    errorsInclude (string) {
      return this.errors.indexOf(string) !== -1
    },
  }
})

We've added errorsInclude which returns true or false. With this, we can determine whether or not to add an error message, or styling to our markup. If there's an error, our <label> tag will attach a class name of error.

vuejs-form-validation

Form validation doesn't have to be complex, it only takes time to implement. Implementation takes place on both client-side and server-side. Here I only demonstrated client-side. Need a demo? Click here.