2
votes

Using Redux-form, I'm running into issues with validation.

I would like to access the store for referencing a piece of state in validation.

I have standard redux form export:

function mapStateToProps({address_object}) {
  return{
    address_object: address_object}
}

    export default reduxForm({
      form: 'wizard',
      destroyOnUnmount: false,
      forceUnregisterOnUnmount: true,
      validate,
    })(
      connect(mapStateToProps,mapDispatchToProps)(WizardFormFirstPage)
    );

and my validate function:

const validate = (values, props) => {
  console.log("DEBUG :",props)
... if / else etc

which lets me gets at the props of the form

however I would like to run validation against something that is stored in state. something like:

    if (<something in state> === values.<thing>) {
 errors.field = "broken"}

console logging the props that validation receives, I can't get it to see anything in state. I can see the address_object in the WizardFormFirstPage component obviously (so actions and reducers are working fine)

Do I need to declare the validate function inside the component (that's connected with mapStateToProps) in order to access this.props.whatever ?? If thats the case, does it work if I call it from the export reduxForm()??

redux noob - apologies if dumb question

2

2 Answers

2
votes

Your almost there.

When you connect your form add the state you need for validation in mapStateToProps.

The state will then be available in the validate props:

reduxForm({
    form: 'wizard',
    validate => (values, { stateForValidation }) => { 
        if(values.myField === stateForValidation)) {
            errors.myField = 'invalid'
        }
    }
})(connect(
    ({ stateForValidation }) => ({ stateForValidation })
)(form))
0
votes

If anyone cares I ended up handling validation at the Field level with

<Field
validate={this.validateAddress} ...> 

then the component method:

validateAddress = () => { 
errors = {} 
// validation stuff
errors._error = "string to display" //use this instead of errors.fieldname = ""
return errors
}

which gave me access to props. However @pariesz answer above answers this question much better.