Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux form - how to set fields as touched

I'm working with form that consists of multiple pages and I want to solve validation.

When I hit Submit button all fields on the present page shows error messages beneath, but if I change the page then I need to hit submit again because these fields weren't set as touched.

My problem would be solved if I could for example set all fields on the page as touched, once the form has flag anyTouched: true.

I'm using redux-form: '^6.0.0-rc.4' and I have one container where I include redux-form and multiple components consisting of fields.

like image 442
Jan Omacka Avatar asked Sep 01 '16 13:09

Jan Omacka


People also ask

How do you reset the form after submit in Redux form?

Just for the record, you can just call props. reset() on the component which has the reduxForm HOC. No extra line of code required.

What is pristine in react?

[00:28] In order to do that, there's actually pristine property from React Final Form. The pristine property is a Boolean value which is true whenever the form is completely empty. It's false when at least something has been written, if the form has been touched in any way.

Should I store form data in Redux?

There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times.

How does Redux handle form?

Redux Form is very easy to use and implement, we just have to wrap our form component with the HOC provided by Redux Form and we are good to go. Applying validation to the form is very easy in Redux Form, we can apply validation to all the fields as well as validations for individual fields.


1 Answers

In redux-form 7.4.2. This can be achieved by checking to see if the form is valid.

If valid you can can load one of your other pages. If the form is not valid, use reduxForms getFormSyncErrors selector and pass in the keys returned by this object to the reduxForm touch property.

import React, { Component } from 'react'
import { compose } from 'redux';
import { connect } from 'react-redux';
import { reduxForm, getFormSyncErrors } from 'redux-form';

class MyComponent extends Component {

  ...

  this.props.valid ? 
    // navigate away 
    : this.props.touch(...Object.keys(this.props.formErrors))

  ...

}

function mapStateToProps(state) {
  return {
    formErrors: getFormSyncErrors('myForm')(state)
  }
}

export default compose(
  connect(mapStateToProps, null),
  reduxForm({form: 'myForm'})
)(MyComponent)
like image 119
JSON C11 Avatar answered Sep 25 '22 01:09

JSON C11