How to add an error message using HTML 5 Validation with Vue

6.9k views Asked by At

I have followed a nice tutorial about HTML 5 form validation with Vue.js, and I tried too many times to add a message error next to the failed input but I couldn't. this is the tutorial : https://logaretm.com/blog/2019-05-03-html-aided-vuejs-form-validation/

This is my code:

function updateMessage(el, vm) {
  vm.errors = Object.assign({}, vm.errors, {
    [el.name]: el.validationMessage
  });
}

export const ValidateMixin = {
  data: () => ({
    errors: {}
  }),
  computed: {
    hasErrors() {
      // Check if we have errors.
      return Object.keys(this.errors).some(key => {
        console.log(this.errors)
        return !!this.errors[key];
      });
    }
  },
  directives: {
    validate: {
      bind(el, _, vnode) {
        const vm = vnode.context;
        el.addEventListener("input", e => {
          updateMessage(e.target, vm);
        });
        vnode.context.$on("validate", () => {
          updateMessage(el, vm);
        });
      }
    }
  },
  methods: {
    validate() {
      this.$emit("validate");
    }
  }
};

i would like to show the error message in a span next to each input field

1

There are 1 answers

0
tony19 On BEST ANSWER

The mixin's errors object property contains a map of element name to validation error messages for that element. For example, entering an invalid email address into the input for <input name="myEmail" type="email" v-validate> would create a validation message in errors.myEmail.

You could use that errors object in the template to bind an element's error messages to a span next to the corresponding input:

<input name="myEmail" type="email" v-validate>
<span v-if="errors.myEmail">{{ errors.myEmail }}</span>

demo