mdg:validation-error

v0.1.0Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

ValidationError

meteor add mdg:validation-error

Use a validation error to indicate that a method call has failed and the client can fix it by changing specific arguments. Examples:

  1. An argument isn't of the right type
  2. A number argument isn't in the right range
  3. A username wasn't found in the database

This kind of error is tied to a specific field so that you can display it next to an input in a form currently being filled by the user.

This error format is based on the error output of aldeed:simple-schema.

API

new ValidationError(errors: Array)

errors must be a array with keys of the form:

1[
2  {
3    // Name of the field this error is about
4    name: String,
5
6    // Type of error, can be mapped to a nice message
7    // on the client
8    type: String,
9
10    // Any kind of details, depends on the type of error.
11    // Should probably include a `value` field that
12    // contains the invalid value passed from the client.
13    details: Object
14  }
15  ...
16]

Usage example

1// Inside a method definition
2saveProduct({ name, cost, category }) {
3  if (cost > 1000) {
4    throw new ValidationError([
5      {
6        name: 'cost',
7        type: 'out-of-range',
8        details: {
9          value: cost,
10          min: 0,
11          max: 100
12        }
13      }
14    ]);
15  }
16
17  // ... the rest of the method
18}

You might catch the error returned by a method call and display it in the UI:

1Template.foo.events({
2  'submit': (event, instance) => {
3    Meteor.call('method', (err) => {
4      if (err && err.error === ValidationError.ERROR_CODE) {
5        _.each(err.errors, function(error) {
6          instance.state.set(`error-${error.name}`: error.type);
7        });
8      }
9    });
10  }
11});

Works out of the box with mdg:method

This type of error is automatically thrown for invalid arguments if you use the mdg:method package, where you can specify a schema for the arguments of your method.