2
votes

I am using @hapi/joi for express validation and sanitation. When validating, certain validators are not working. In this one, not only does trim() not validate for white space at the beginning and end of the input string but it also does not trim it as it is supposed to given that convert is set to true by default. However, the check for valid email and required both work and throw their respective errors. I also tried lowercase() and that did not validate or convert it to lowercase.

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

const string = Joi.string();

const localRegistrationSchema = Joi.object().keys({
  email: string
    .email()
    .trim()
    .required()
    .messages({
      "string.email": "Email must be a valid email address",
      "string.trim": "Email may not contain any spaces at the beginning or end",
      "string.empty": "Email is required"
    })
});
1

1 Answers

5
votes

With version >= 17 of Joi you could write the schema as followed:

const localRegistrationSchema = Joi.object({ // changes here,
  email: Joi.string() // here
    .email()
    .trim()
    .lowercase() // and here
    .required()
    .messages({
      'string.email': 'Email must be a valid email address',
      'string.trim': 'Email may not contain any spaces at the beginning or end', // seems to be unnecessary
      'string.empty': 'Email is required'
    })
});

console.log(localRegistrationSchema.validate({ email: '' }));
// error: [Error [ValidationError]: Email is required]

console.log(localRegistrationSchema.validate({ email: '  [email protected]' }));
// value: { email: '[email protected]' }

console.log(localRegistrationSchema.validate({ email: '[email protected]  ' }));
// value: { email: '[email protected]' }

console.log(localRegistrationSchema.validate({ email: '[email protected]' }));
// value: { email: '[email protected]' }