jurassix / react-validation-mixin

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

Auto label field keys in validation messages #4

Closed ivan-kleshnin closed 9 years ago

ivan-kleshnin commented 9 years ago

To recap

Messages like "serialNumber must be a number" are not very friendly. Joi provides an option to override key name in message with label method.

validatorTypes: function() {
  return {
    serialNumber: Joi.number().required().label("Serial Number"),
    assemblyDate: Joi.date().required().label("Assembly Date"),
    manufacturer: Joi.string().required().label("Manufacturer),
  };
}

But you, probably, have already defined that labels in your form declaration and don't want to repeat it again. To manually handle this it's possible to make validatorTypes a function and access field labels by this.refs.

validatorTypes: function() {
  return {
    serialNumber: Joi.number().required().label(this.refs.serialNumber.props.label),
    assemblyDate: Joi.date().required().label(this.refs.assemblyDate.props.label),
    manufacturer: Joi.string().required().label(this.refs.manufacturer.props.label),
  };
},

It's a bit more in-sync, but even more verbose :(


It's really verbose so my suggestion was to add autoLabel propety which could automate this tedious label passing.


autoLabel: true // to auto label ALL fields

**OR**

autoLabel: [ // to auto label defined fields
  "serialNumber",
  "assemblyDate"
]

The one of possible alternatives I considered is tweaking validatorTypes return type:

validatorTypes: function() {
  return {
    serialNumber: [Joi.number().required().label(), true], // this is not obvious
    assemblyDate: {validator: Joi.date().required().label(), autoLabel: true}, // this  is too verbose 
    manufacturer: Joi.string().required().label(),
  };
},

I like first approach more because it decouples one task from another. validatorTypes is already complex enough (accounting it can be map, function... – requires a lot of documentation already).

Name autoLabel is probably too generic. Even native React methods are longer (shouldComponentUpdate...). So now I think it's better to call it autoLabelValidations or even autoLabelValidationMessages.

Do you have ideas how this auto-labeling may be implemented differently?

jurassix commented 9 years ago

Thanks for breaking this out separately. I hope to work on this after issue #3 is resolved.

jurassix commented 9 years ago

I'm not sure this library is going to support introspection of the user form. I'm closing this issue as there is currently no like functionality in this library. I feel that a consumer of this library can add this abstraction easily and produce a tool/library with these features.