jurassix / react-validation-mixin

Simple validation mixin (HoC) for React.
MIT License
283 stars 38 forks source link

How to get error types? #26

Closed skfd closed 9 years ago

skfd commented 9 years ago

I want to build username input component.

It must have different tooltips for different validation errors, like "You can't have weird characters in your username", "Username is too short", "username is required" and so on. For example:

Joi.string().alphanum().min(3).max(30).required()

All I found is this.state.errors that contains descriptions of a problem, that I can't customise.

username: ['"Имя" is not allowed to be empty']

Is there a way to get error in more formal way suitable for customisation and localisation?

username: [required: '"Имя" is not allowed to be empty']

Am I missing something?

jurassix commented 9 years ago

There are many issues with Joi on custom validation messages. This on particularly seems to provide what you, and many people, will need; https://github.com/hapijs/joi/issues/546

Bellow is a typical Joi validation response. In this library we only grab the path and message and push them onto this.state.errors. I can easily add the type and a convenience method so you can access it. Then in your code you can build custom messages for this field given specific errors. But it could get verbose for you.

This change would not take long if you think it would be useful.

[ {
  message: '"zulassung" length must be 5 characters long',
  path: 'zulassung',
  type: 'string.length',
  context: [Object] 
  },  { 
  message: '"name" is required',
  path: 'name',
  type: 'any.required',
  context: [Object] 
}]
jurassix commented 9 years ago

This has now been documented. Custom messages is fully supported by Joi.

Checkout the docs on Custom Messages and I18N