Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom validator function in Joi?

I have Joi schema and want to add a custom validator for validating data which isn't possible with default Joi validators.

Currently, I'm using the version 16.1.7 of Joi

   const method = (value, helpers) => {
      // for example if the username value is (something) then it will throw an error with flowing message but it throws an error inside (value) object without error message. It should throw error inside the (error) object with a proper error message

      if (value === "something") {
        return new Error("something is not allowed as username");
      }

      // Return the value unchanged
      return value;
    };

    const createProfileSchema = Joi.object().keys({
      username: Joi.string()
        .required()
        .trim()
        .empty()
        .min(5)
        .max(20)
        .lowercase()
        .custom(method, "custom validation")
    });

    const { error,value } = createProfileSchema.validate({ username: "something" });

    console.log(value); // returns {username: Error}
    console.log(error); // returns undefined

But I couldn't implement it the right way. I read Joi documents but it seems a little bit confusing to me. Can anyone help me to figure it out?

like image 313
Shifut Hossain Avatar asked Oct 17 '19 05:10

Shifut Hossain


People also ask

What is a custom validator?

The CustomValidator control is a separate control from the input control it validates, which allows you to control where the validation message is displayed. Validation controls always perform validation on the server.

Which is better express validator or Joi?

Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.


2 Answers

const Joi = require('@hapi/joi');

Joi.object({
    password: Joi
        .string()
        .custom((value, helper) => {

            if (value.length < 8) {
                return helper.message("Password must be at least 8 characters long")

            } else {
                return true
            }

        })

}).validate({
    password: '1234'
});
like image 95
Muslim Omar Avatar answered Oct 31 '22 20:10

Muslim Omar


Your custom method must be like this:

const method = (value, helpers) => {
  // for example if the username value is (something) then it will throw an error with flowing message but it throws an error inside (value) object without error message. It should throw error inside the (error) object with a proper error message

  if (value === "something") {
    return helpers.error("any.invalid");
  }

  // Return the value unchanged
  return value;
};

Docs:

https://github.com/hapijs/joi/blob/master/API.md#anycustommethod-description

Output for value :

{ username: 'something' }

Output for error:

[Error [ValidationError]: "username" contains an invalid value] {
  _original: { username: 'something' },
  details: [
    {
      message: '"username" contains an invalid value',
      path: [Array],
      type: 'any.invalid',
      context: [Object]
    }
  ]
}
like image 38
SuleymanSah Avatar answered Oct 31 '22 22:10

SuleymanSah