jurassix / react-validation-mixin

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

Implement isDirty() functionality. #58

Open 40818419 opened 8 years ago

40818419 commented 8 years ago

Let's imagine we got a Button in a form which suppose to be disabled when required fields in a form are empty. Basically we should prevent user to click / fire event on enter when form is invalid.

Output should be like e.g:

<button disabled={!this.props.isValid() && this.props.isDirty() } > Sign in</button>
jurassix commented 8 years ago

This seems to be a common request; provide a way to silently validate the form.

Something like:

this.props.validate({
  silent: true,
});

However, there are many issues with this implementation since validate() is async.

jurassix commented 8 years ago

Well after a little more thought, it would not be hard to handle the async validation.

this.props.validate({
  silent: true,
}, (nextErrors) => {
  this.setState({
    disableSignin: isEmpty(nextErrors),
  });
});
<button disabled={this.state.disableSignin}>Sign in</button>
webholics commented 8 years ago

+1 We need a way to validate without changing the state of the component (in a true functional way) as proposed with the silent argument.

jurassix commented 8 years ago

@webholics u interested in putting together a PR? I will prioritize this work otherwise.

webholics commented 8 years ago

Unfortunately I discovered that the silent flag doesn't even solve our problem. Since the validate function is async I don't really know where to put it in the lifecycle of our form component to guarantee that the button is always disabled when the data is invalid.

Question: Why is validate() async? Joi's validate method can be used synchronously? This would make things much easier.

jurassix commented 8 years ago

At this point I think we should stick with async validation. I do see what you mean about lifecycle's here. There may be a declarative solution in here, I think need to think about it more. If you have ideas please share. I'll do the same.

webholics commented 8 years ago

We could do basically the same as Joi does by letting validate() only behave async if a callback is provided and otherwise use the sync version. This way we wouldn't have any breaking changes. But I'm not sure if having a sync version is possible with other validation strategies you may want to support in future.