[Vuejs]-How to write a custom / generic validation for the input fields using vee-validation in vuejs2

0👍

You can pass an object to your custom validation (and even return it in a method) :

<input placeholder="Enter your name" v-validate="validations('firstName')">
created() {
  Validator.extend('fieldName', {
    getMessage(field, val) {
      return `Enter valid ${val}`
    },
    validate(value, field) {
      if (field == 'firstName') { return /^[a-zA-Z]*$/.test(value) }
      else if (field == 'lastName') { return  /^[a-z]*$/.test(value) }
      // and so on
    }
  })
},
methods: {
  validations(field) {
    return { required: true, fieldName: field }
  }
}

Leave a comment