react-validation
react-validation copied to clipboard
How to check if <Form /> is valid
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 />
Can't believe this isn't listed in doc. I also want to ask the same.
Is there a solution to this question? I wonder how the <Button />
is getting disabled if there are any errors?
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.
+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?
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?
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.
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.