BootstrapVue Vuelidate Custom Error Message For Each Validator Rule

July 27, 2021
<template>
  <div>
    <b-form ref="form" @submit.prevent="submit">
      <b-form-group
        label="Name"
        label-for="input-name"
        invalid-feedback="Name is required"
      >
        <b-form-input
          :state="validateState($v.item.name)"
          id="input-name"
          v-model="$v.item.name.$model"
        ></b-form-input>
      </b-form-group>

      <b-form-group
        label="Url"
        label-for="input-url"
      >
        <b-form-input
          :state="validateState($v.item.url)"
          id="input-url"
          v-model="$v.item.url.$model"
        ></b-form-input>

        <b-form-invalid-feedback v-if="!$v.item.url.required">
          URL is required
        </b-form-invalid-feedback>
        <b-form-invalid-feedback v-else-if="!$v.item.url.url">
          URL is invalid
        </b-form-invalid-feedback>
        <b-form-invalid-feedback v-else-if="!$v.item.url.allow">
          URL is not allowed
        </b-form-invalid-feedback>

      </b-form-group>


      <b-button type="submit" variant="primary">Submit</b-button>
    </b-form>
  </div>
</template>

<script>
import { validationMixin } from "vuelidate"
import { required, url, minLength } from "vuelidate/lib/validators"

export default {
  mixins: [validationMixin],
  // props: ['item'],
  data() {
    item: {
      name: 'Desmond'
    },
  },
  validations: {
    item: {
      name: {
        required
      },
      url: {
        required, 
        url,
        allow(value) {
          const urlObj = new URL(value)
          if (urlObj.hostname == 'google.com')
            return false
          return true
        }
      }
    }
  },
  methods: {
    validateState(item) {
      const { $dirty, $error } = item
      return $dirty ? !$error : null
    },
    submit() {
      this.$v.item.$touch()
      if (this.$v.item.$anyError)
        return false

      console.log(this.item)
      alert("Form submitted!")
    }
  }
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.