DEV Community

Jonathan Flower
Jonathan Flower

Posted on • Edited on

2

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/

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more