Search code examples
reactjsvalidationerror-handlingjoi

How can I set a standard message for Joi.ref?


I am currently using Joi validation for my project. The relevant values are price and maximum price, where maximum is optional but must be bigger than price.

I am using Joi.number().greater(Joi.ref('price')) for maximum price and I get the error: "maxPrice" limit references "ref:price" which must be a number when I leave price empty.

How can I set a custom message for this?

(I have read the documentation, but couldnt find anything that worked for me.


Solution

  • Refer to this link for answer How to set Joi validations with custom messages??

    Here is the answer copied from the link posted.

    const Joi = require('joi');
    
    const schema = Joi.object({
            username: Joi.string().alphanum().min(3).max(16).required().messages({
                "string.base": `Username should be a type of 'text'.`,
                "string.empty": `Username cannot be an empty field.`,
                "string.min": `Username should have a minimum length of 3.`,
                "any.required": `Username is a required field.`,
              }),
              password: Joi.string().required(),
              password_repeat: Joi.any().valid(Joi.ref('password')).required().messages({
                "any.only" : "Password must match"
              })
    });