react-validation icon indicating copy to clipboard operation
react-validation copied to clipboard

Returns a boolean after validation

Open cheton opened this issue 6 years ago • 4 comments

  • Added a hasErrors() method to return a boolean value
  • validate() and validateAll() will return a boolean value after validation.

This PR enables support for the following use case.

<button
    type="button"
    onClick={event => {
        const ok = this.form.validateAll();
        if (!ok) {
            return;
        }

        const { name, password } = this.form.getValues();
        // Save changes
    }}
>
    Save
</button>

cheton avatar Oct 23 '17 14:10 cheton

@cheton , did you tested it? I believe on that loop errors setup isn't made yet since _setErrors called asynchronously and hasErrors will get prevState.

Lesha-spr avatar Oct 23 '17 15:10 Lesha-spr

Sorry for that I did make a mistake, the _setErrors callback is asynchronous and it will be called when the component state has actually updated.

How about using an error-first callback for the validate function?

this.form.validateAll((err) => {
    if (err) {
        return;
    }

    const { name, password } = this.form.getValues();
    // Save changes
});

cheton avatar Oct 23 '17 15:10 cheton

I made a little change to the code using the error-first callback, this should fix the issue existed in this PR.

cheton avatar Oct 23 '17 16:10 cheton

I'd love this feature to validate the whole form before submitting. I have to do I manually with refs to all inputs inside a form and it's awful.

jayu avatar Jul 24 '18 14:07 jayu