Vue3: How to add a custom HTML5 validation method to a Vue component.


To use the setCustomValidity() method in a Vue 3 component, you will need to create a reference to the element in your component's template you want to add the custom validation rule to. You can do this using the ref directive.

Here is an example of how you can use setCustomValidity() in a Vue 3 component. In this example, we will only allow the word tacos as a valid input of the text box.

<template>
  <form>
    <label for="myInput">Enter a value:</label>
    <input ref="myInput" id="myInput" type="text" v-model="inputValue" @input="checkValue" />
  </form>
</template>

<script>
export default {
  data() {
    return {
      inputValue: '',
    };
  },
  methods: {
    checkValue() {
      if (this.$refs.myInput.value.toLower() !== "tacos") {
        this.$refs.myInput.setCustomValidity('Tacos are the only answer.');
      } else {
        this.$refs.myInput.setCustomValidity('');
      }
    },
  },
};
</script>

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.