Getting the human readable error messages from SimpleSchema

I’m trying to put together a React update form that displays validation error messages below the various input fields.

I’m using Simple Schema to validate the data. The validation error it throws for an invalid object seems to have a child collection of broken rules, but to only have the human readable message for the first validation error, so if two or more fields are not valid you only get a nicely worded message for the first one.

Is there a way to ask the Schema for the human readable error message for each broken rule?

This is what the validation error contains:

details: Array[2]
0: Object
details: Object
name: "email"
type: “regEx”

1: Object
details: Object
name: "postcode"
type: “maxString”

error: "validation-error"
errorType: "Meteor.Error"
message: "Email must be a valid e-mail address [validation-error]"
reason: “Email must be a valid e-mail address”

This code is from collection2 but it may help you anyway. I’m not sure if it hits any collection2 code.

// Keep our internal state pure. If we use the state when inserting (and
// the insert fails) then the state will get polluted with the schema's
// auto generated values.
const lead = { ...this.state.lead };

const fieldErrors = {};
const context = Leads.simpleSchema().namedContext();
context.validate({ $set: lead }, { modifier: true });
context.invalidKeys().forEach(invalidKey => {
  fieldErrors[invalidKey.name] = context.keyErrorMessage(invalidKey.name);
});
this.setState({ errors: fieldErrors });
1 Like

Thanks @timfletcher, that’s really good thinking to look at collection2. The context.keyErrorMessage() method is exactly the one I was looking for.