From e8f0a21d35d19c635172420c072507d3f868f54b Mon Sep 17 00:00:00 2001 From: Dylan Smith Date: Mon, 15 May 2017 12:41:45 +0100 Subject: [PATCH] feat(validateSchema): support custom error generation --- demo/src/index.js | 6 ++++++ src/validateSchema.js | 14 ++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/demo/src/index.js b/demo/src/index.js index 6a382e9..0fbc5fc 100644 --- a/demo/src/index.js +++ b/demo/src/index.js @@ -81,6 +81,12 @@ const createFormContainer = compose( username: { required: true, maxLength: 8, + // note: you can optionally generate custom errors via `formatError` + // by providing a string or a function that receives context + formatError: (context) => { + // e.g. return a message id for use with `react-intl` or similar + return `errors.username.${context.condition}`; + } }, password: { // note: my `test` implementation is super basic, `fail` can diff --git a/src/validateSchema.js b/src/validateSchema.js index bd023f4..918e360 100644 --- a/src/validateSchema.js +++ b/src/validateSchema.js @@ -8,20 +8,26 @@ const getValidationErrors = (schema, model) => Object.keys(schema).reduce((acc, const value = model[key] const rules = schema[key] + const renderError = (condition, fallback) => { + return typeof rules.formatError === 'function' + ? rules.formatError({ key, value, condition, rules, schema, model }) + : fallback + } + if (rules.required && !value) { - errors.push(`${key} is required`) + errors.push(renderError('required', `${key} is required`)) } if (rules.type && typeof value !== rules.type) { - errors.push(`${key} must be of type ${rules.type}, but got ${typeof value}`) + errors.push(renderError('type', `${key} must be of type ${rules.type}, but got ${typeof value}`)) } if (rules.minLength) { if (!value || value.length < rules.minLength) { - errors.push(`${key} must have at least ${rules.minLength} characters`) + errors.push(renderError('minLength', `${key} must have at least ${rules.minLength} characters`)) } } if (rules.maxLength) { if (value && value.length > rules.maxLength) { - errors.push(`${key} must not have more than ${rules.maxLength} characters`) + errors.push(renderError('maxLength', `${key} must not have more than ${rules.maxLength} characters`)) } } if (rules.test) {