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>
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.
Top comments (0)