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

How to check if <Form /> is valid

Open cblaettl opened this issue 7 years ago • 7 comments

Before the breaking changes I was able to do:

const validationErrors = this.form.validateAll()
if (Object.keys(validationErrors).length !== 0) {
    // Form has some validation errors
}

How can I achieve that with the new version? Thanks, for this awesome library. :)

Edit: this.form is a reference to <Form />

cblaettl avatar Oct 25 '17 08:10 cblaettl

Can't believe this isn't listed in doc. I also want to ask the same.

alipoaglio avatar Oct 25 '17 10:10 alipoaglio

Is there a solution to this question? I wonder how the <Button /> is getting disabled if there are any errors?

cblaettl avatar Oct 30 '17 06:10 cblaettl

If you guys are still interested about this try:

this.form.getChildContext()._errors

This should return an array that is populated with the ids of the components that have errors.

where this.form is a reference to <Form />.

I'm going to create a pull request in which i'll add a method to check for errors. Let's hope it will be accepted.

romeobalta avatar Nov 13 '17 12:11 romeobalta

+1 on this - what's the point of a validation library if you can't test whether or not the form as a whole is valid?

ryangiglio avatar Jan 18 '18 02:01 ryangiglio

Couldn't you just implement the HOC method for a button (because that can handle this), which receives a prop called hasErrors, and then use that prop for the disabled attribute? This is how I am using it:

import { button } from 'react-validation'

const _Button = ({ hasErrors, ...props }) => <button {...props} disabled={hasErrors} />

export const Button = button(_Button)

The button will be disabled until all of the errors are resolved.

If this does not address your use case, could you describe in more detail what exactly you are trying to do?

eruby94 avatar Feb 21 '18 16:02 eruby94

I am facing same problem with validateAll method. this.form.validateAll() is not returning the list of errors. Please share if there is any solution for this.

srujanganta avatar Mar 22 '18 22:03 srujanganta

The solution to this is definitely a bit annoying but it's not particularly cumbersome; to expand on @romeobalta's point:

handleSubmit = event => {
  event.preventDefault()

  if (this.form.getChildContext()._errors.length === 0) {
    // valid
  } else {
    // invalid
  }
}

Keep in mind you still have to call this.form.validateAll() to force error population.

handlebauer avatar Mar 23 '18 01:03 handlebauer