Nishant Sharma
Nishant Sharma

Reputation: 23

Joi validation : minimum length function is not working

const Joi = require('joi');
app.post('/api/courses', (req, res) => {
  const schema = {
    name: Joi.string().min(3).required()
  };
  const result = Joi.validate(req.body, schema);
  if (result.error) {
    res.status(400).send(result.error.details[0].message); 
    return;
  }
  const course = {
    id: courses.length + 1,
    name: req.body.name
  };
  courses.push(course);
  res.send(course);
});

when I post in postman a blank object is then 400 give "name" is required but if I post "name": "1" then again output is same instead of minimum length should be of 3 characters.

Upvotes: 2

Views: 11667

Answers (2)

livingstone
livingstone

Reputation: 31

Check your model and be sure that the type is string, like so: type: String. This should fix the issue. Joi's min() function seems to operate only on strings.

Upvotes: 0

Wes Tyler
Wes Tyler

Reputation: 140

I cannot replicate the issue. If you provide some more details and failing examples we might be able to help.

Joi.string().min(3).required().validate('a'); // ValidationError: "value" length must be at least 3 characters long

const objSchema = {name: Joi.string().min(3).required()};

Joi.validate({}, objSchema); // ValidationError: child "name" fails because ["name" is required]
Joi.validate({name: 'a'}, objSchema); // ValidationError: child "name" fails because ["name" length must be at least 3 characters long]

Joi.version; // '14.3.1'

Upvotes: 3

Related Questions