[Vuejs]-How does validation work in Vue.js 2.0?

0👍

Vue.js 2 validation is very similar to Vue.js version 1. It can only validate props out of the box. There are 6 ways to do that, according to the documentation:

Vue.component('example', {
  props: {
    // basic type check (`null` means accept any type)
    propA: Number,
    // multiple possible types
    propB: [String, Number],
    // a required string
    propC: {
      type: String,
      required: true
    },
    // a number with default value
    propD: {
      type: Number,
      default: 100
    },
    // object/array defaults should be returned from a
    // factory function
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // custom validator function
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
}) 

If you want to have input validation, you need to use a library. The most popular one is vue-validator.

After you add it to your Vue app as a plugin (via Vue.use(...)), you can validate input like so:

<div id="app">
  <validator name="validation1">
    <form novalidate>
      <div class="username-field">
        <label for="username">username:</label>
        <input id="username" type="text" v-validate:username="['required']">
      </div>

      </div>
      <div class="errors">
        <p v-if="$validation1.username.required">Required your name.</p>
      </div>
      <input type="submit" value="send" v-if="$validation1.valid">
    </form>
  </validator>
</div>

Leave a comment