jurassix / react-validation-mixin

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

Adds a filter to test the existence of errors after validating #82

Closed ehkasper closed 7 years ago

ehkasper commented 7 years ago

When using validate with a field as param, as in: this.props.validate('email') in a form with multiple fields, the errors state may have the following format:

errors: {
  email: Array(1),
  name: Array(1)
  ...etc
}

if I do not have any errors it gets the following format:

errors: {
  email: Array(0),
  name: Array(0)
  ...etc
}

If I do not call this.props.validate() (without passing the field) the isValid method returns false, even though there are no errors. Im using react-validatorjs-strategy as a strategy.

So, I thought of doing this workaround and testing whether there are errors or not, and passing the empty errors object if there arent. I'm using loadash.values and filter to prevent adding new more libs.

What do you think? Am I missing anything?

Thanks in advance!

jurassix commented 7 years ago

@ehkasper I think the easiest path to get what you want is to wrap the strategy you are using and change the behavior of the validator. Reference: https://jurassix.gitbooks.io/docs-react-validation-mixin/content/overview/strategies.html

For example, if you are using the react-validatorjs-strategy do something like the following:

const customStrategy = {
  ...strategy,
  validate: (data, schema, options, callback) => {
    // delegate to strategy but enhance the callback to change behaviour
    strategy.validate(data, schema, options, (error) => {
      // update error object as needed then pass it to callback, which will call setState on the errors
      callback(error);
    });
  },
};
validation(customStrategy)(Component);

I think you have enough of an escape hatch here to work make your needs work without having to change the behavior of this mixin. Paste some code if you need help getting this working. Good luck!

ehkasper commented 7 years ago

@jurassix makes sense. Thank you!

As a note, I think it'd be a good idea to standardize the errors object. If im not mistaken, different strategies may treat it differently, and alter the behaviour of methods such as isValid.

Thanks again :)

jurassix commented 7 years ago

@ehkasper yup errors object should be standardized. I think this mixin handles both null, and empty array. Feel free to update the docs if you would like: https://github.com/jurassix/docs-react-validation-mixin