Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi validation string().trim() not working

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"
    })
});
like image 285
Joel Jacobsen Avatar asked Jul 31 '26 06:07

Joel Jacobsen


1 Answers

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]' }
like image 186
pzaenger Avatar answered Aug 03 '26 03:08

pzaenger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!