DEV Community 👩‍💻👨‍💻

Jonathan Flower
Jonathan Flower

Posted on • Updated on

Vue and HTML5 Form Validation

The browser form validation has gotten better over the years and I have started to find simply adding some minor customization to the HTML5 form validation effective and a huge time saver.

For the times you want a custom error message along with a regex pattern:

<template>
  <input type="tel" pattern="^[0-9]{5}?$" required name="zipCode" v-model.trim="zipCode" @keyup="customInvalid" />
</template>

<script setup lang="ts">
const zipCode = ref('');
interface InputTextKeyboardEvent extends KeyboardEvent {
  currentTarget: HTMLInputElement;
}

const customInvalid = (e: InputTextKeyboardEvent) => {
  if (e.currentTarget.validity.patternMismatch) {
    e.currentTarget.setCustomValidity('Please enter a valid 5 digit US Postal Code');
  } else {
    e.currentTarget.setCustomValidity('');
  }
};
</script>

Enter fullscreen mode Exit fullscreen mode

The key to the above solution is using the @keyup. This way it re-evaluates the validity after the browser updates the validity. This is the only event I could find that allowed me to hide the error message as soon as the user enters a valid value.

ref:
https://reactgo.com/html5-custom-validation-message/

Top comments (0)

Create an Account!

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.