Validation

Validation can be set up against each field and can take a function or a string to evaluate against. The required attribute can also be set to make this a required field. For example:

let vm = new Vue({
  el: '#app',
  data: {
    form: {
      name: {
        type: 'text',
        required: true
      },
      lname: {
        type: 'text',
        validators: {
          length: 'field.value.length > 3'
        }
      },
      email: {
        type: 'text',
        required: true,
        validators: {
          looksOk: function(field){
            return field.value.indexOf('@') >= 0;
          }
        }
      }
    }
  }
});

In the above example the name field is required, the lname field must be longer than 3 characters and the email field must have a '@' present and is also required.

Errors

Errors are stored in the $errors field on the form. Using the above example, if we dumped vm.form.$errors we would see the following structure:

//vm.form.$errors
{
  name: {
    required: true
  },
  lname: {
    length: true
  },
  email: {
    required: true,
    looksOk: true
  }
}

Errors will be true if there is an error ( ie, the field is invalid ) and will become false when their expectation is met.

Valid state

There is also a $valid attribute that is added to the form and is toggled between true and false if all the errors are clear. In the above example, when the user first loads the form, vm.form.$valid will be false as there are required fields. Once they've filled in those fields and the criteria is met, vm.form.$valid will become true.

results matching ""

    No results matching ""