1
votes

In using redux-form with React, I'm having an issue where the error messages are not displaying for field-level input validation.

Here is the relevant code from the component:

const renderField = ({input, placeholder, type, meta: {touched, error, warning}}) => (
  <div>
    <input {...input} placeholder={placeholder} type={type} />
    {touched &&
      ((error && <span>{error}</span>) ||
        (warning && <span>{warning}</span>)
      )
    }
  </div>
)

const required = value => {
  console.log("required");
  return value ? undefined : 'Required';
};

const Question = props => {
  const { handleSubmit, onBlur, question, handleClick } = props;    
  return (
    <div className={`question question-${question.name}`}>
      <form className={props.className} onSubmit={handleSubmit}>
        <div className='question-wrapper'>
          <label className={`single-question-label question-label-${question.name}`}>{question.text}</label>
          <Field
            component={renderField}
            type={question.type}
            name={question.name}
            placeholder={question.placeholder}
            onBlur={onBlur}
            validate={required}
          />
        </div>
      </form>
    </div>
  )
}

export default reduxForm({
  form: 'quiz',
  destroyOnUnmount: false,
  forceUnregisterOnUnmount: true,
})(Question);

When I test it, I see that in the console the UPDATE_SYNC_ERRORS action is being called, and the console.log("required"); is also showing up. But when I navigate to the next question, neither on the screen do I see the error message, nor do I see any evidence of it when I inspect the component with DevTools.

I've been following the example on Field-Level Validation shown in the redux-form docs here: http://redux-form.com/6.7.0/examples/fieldLevelValidation/

Any idea what could be causing this? Thanks in advance!

2
show me your code to reduxForm() helper? - Ravindra Ranwala
Just added it to the code above. Does it need the validate value? I didn't see it in the example on redux-form.com/6.7.0/examples/fieldLevelValidation - Alacritas
Although even when I add the required function to the helper, it doesn't seem to make a difference. - Alacritas
Remove this line: onBlur={onBlur}. - wesley6j

2 Answers

1
votes

Well, you have to write a validate function, and pass it to the reduxForm helper or wrapper like this. Redux-form will pass all the form values to this function before the form is submitted.

function validate(values) {
  const errors = {};

  // Validate the inputs from 'values'
  if (!values.name) {
    errors.name = "Enter a name!";
  }

   ...

  return errors;
}

export default reduxForm({
  validate,
  form: 'QuestionForm'
})(
  connect(null, { someAction })(Question)
);

Hope this helps. Happy Coding !

0
votes

you can also provide validate like this

const formOptions = {
  form: 'yourformname',       
  validate: validatefunctionname,redux-form
};