Skip to content
This repository has been archived by the owner on Jan 22, 2023. It is now read-only.

Commit

Permalink
feat(validateSchema): support custom error generation
Browse files Browse the repository at this point in the history
  • Loading branch information
dylansmith authored and David Zukowski committed May 16, 2017
1 parent bcecd89 commit e8f0a21
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
6 changes: 6 additions & 0 deletions demo/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 10 additions & 4 deletions src/validateSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit e8f0a21

Please sign in to comment.