nijikokun / Validator

JSON Schema validation library for Javascript / Node / Express.
159 stars 21 forks source link

Better error formatting #3

Open badsyntax opened 11 years ago

badsyntax commented 11 years ago

Hi there. Thanks for the module, I've found it to be very useful.

I've noticed some inconstancies with how the errors are generated.

For example, lets say I have the following code:

var Validator = require('./validator');

var schema = {
  date: {
    type: Date,
    required: true,
  },
  title: {
    type: String,
    required: true
  }
};

var validator = new Validator(schema);

Now if I run a check against a data object with no data, I get two validation errors:

console.log(validator.check({}));

/* Outputs:
{ _error: true,
  date: { required: { message: 'This parameter is required.' } },
  title: { required: { message: 'This parameter is required.' } } }
*/

If I run the check against the data object with one incorrect type, I only get one error:

console.log(validator.check({
  date: 'test'
}));

/* Outputs:
{ _error: true,
  title: { required: { message: 'This parameter is required.' } } }
*/

I would expect the above check to return two errors.

It would be useful if all failed checks are returned in the errors object. It would also be useful if the errors were better formatted to allow me to reliably loop through them, something like this:

{
  date: [
    'This parameter is required.',
    'Invalid parameter data type, expected: Date'
  ],
  title: [
    'This parameter is required.',
    'Invalid parameter data type, expected: String'
  ]
}

What do you think?

nijikokun commented 9 years ago

This is old but I will give my thoughts, I think perhaps it should give one for each plugin, but not as strings, for those who want to rely on custom messages they would have to parse strings and that would be a hassle.

lesterzone commented 9 years ago

I'll love something like this:

{
    date: {
        required: 'This parameter is required.',
        type: 'Invalid parameter data type, expected: Date'
    }
}