3

I recently migrated to new joi repo (@hapi/joi => joi)

Now I am getting error when running server

throw new AssertError([result.error.details[0].message]);
        ^

Error: "language" is not allowed

I searched google and SO , but cant find solution

This is my code :

  forgetUser: {
    query: {
      email: Joi.string().regex(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
      .required()
      .options({ language: { string: { regex: { base: 'must be valid' } } } })
      .label('Email')
    }
  },

Please help me?

RagAnt
  • 1,064
  • 2
  • 17
  • 35

2 Answers2

3

This is caused when you are passing an unknown field to a Joi schema.

for example, you have this Joi schema:

Joi.object({
  name: Joi.string().required(),
  email: Joi.string().required(),
});

and you pass this object to validate:

{
  name: "John Doe",
  email: "johndoe@gmail.com",
  language: "en"
}

The validation will throw an error / failed because language is not allowed inside the schema.

To prevent this, you can pass stripUnknown options on the Joi Schema so it will strip unknown fields

Joi.object({
  name: Joi.string().required(),
  email: Joi.string().required(),
}).options({ stripUnknown: true });

or you can pass allowUnknown so it will ignore unknown fields

Joi.object({
  name: Joi.string().required(),
  email: Joi.string().required(),
}).options({ allowUnknown: true });

You can read more about validation options here

Owl
  • 6,337
  • 3
  • 16
  • 30
3

It is not clear from the question what you are trying to achieve (maybe add more details?).

If you are trying to validate email, there is already a built-in function to do so: string.email().

If you still want to do a custom regex matching, there is an built-in function for this too: string.pattern().

If you want to replace the built-in error messages to custom error messages, Joi provides that by using .messages(). Check the answer here: https://stackoverflow.com/a/58234246/1499476.


Basically, you can do something like:

forgetUser: {
    query: {
      email: Joi.string().pattern(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
      .required()
      .label('Email')
      .messages({
        'string.pattern.base': '{#label} must be valid', // --> Email must be valid.
        'string.base': '{#label} should be a type of "text"',
        ... // other customisations
      })
    }
  },

string.pattern() can also be used as alias string.regex() (as you are already doing).

Rvy Pandey
  • 1,654
  • 3
  • 16
  • 22