Custom Error Message for PriceInCents – Vue3 and Vuelidate

Hey everyone,

This is a quick post to show how you can add a custom error message when using Vuelidate in Vue3. In my case I have a price field that should not be greater than $1000. The issue is that I store the amount in cents which results in the following error:

This is obviously a little ambiguous to the user who isn’t aware that everything is running in cents behind the scenes. In order to avoid the issue I used a helper in @vuelidate/validates:

// Import the following in your component
import {
  required,  
  maxValue,
  helpers, // Helpers provides access to the message customisation
} from "@vuelidate/validators";

...

// Add the following validation rule
priceInCents: {
          required,
          maxValue: helpers.withMessage("Price cannot be more than $1000.00" , maxValue(100000)),
        },

With the new rule in place the error is much more useful:

While it doesn’t seem to show up on Google too well this functionality is documented by Vuelidate on the following page: https://vuelidate-next.netlify.app/custom_validators.html#custom-error-messages

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s