guillaumepotier / validator.js

Powerful objects and strings validation in javascript for Node and the browser
http://validatorjs.org
MIT License
255 stars 39 forks source link

Add `throw` option to throw an error with violations #61

Open ricardogama opened 7 years ago

ricardogama commented 7 years ago

Following the concept of having an options argument on the validate method suggested in #60, it would be useful to have a throw option that would enable throwing an error when validation fails, exposing violations on an errors or violations property.

Such feature would facilitate handling validation errors on catch blocks alongside other error, which is a very common practice, for example:

import { Validator, ViolationError } from 'validator.js';

function foo(data) {
  try {
    Validator.validate(data, { bar: is.required() }, { 
      throw: true 
    });

    // ... other code which could throw other custom errors
  } catch (e) {
    if (e instanceof ViolationError) {
      // `e.errors` should contain all raised violations
    }

    // ... handle other errors

    throw e;
  }
}

Enabling this through the options argument will also be a breaking change, so I guess this feature should be discussed with a new major release in mind.

@guillaumepotier @fixe @ruimarinho WDYT?