jasongonzales
jasongonzales

Reputation: 1597

What is a more elegant way to dynamically add validation rules to Redux Form Fields?

I am iterating over an array of objects to form Redux Form Fields and not all fields require user input. Field level validation rules expect a function and I haven't been able to figure out a dynamic function that either returns a validation rule or null.

I currently do this:

  {areaQuestions.map(
      question =>
        question.required ? (
          <Field
            component={SelectField}
            key={question.area}
            label={question.questionText}
            name={question.area}
            placeholder={question.questionText}
            options={question.questionAnswers}
            validate={required}
          />
        ) : (
          <Field
            component={SelectField}
            key={question.area}
            label={question.questionText}
            name={question.area}
            placeholder={question.questionText}
            options={question.questionAnswers}
          />
        ),
    )}

However this approach of just leaving off the validation prop seems inelegant and not DRY. Any other suggestions?

Upvotes: 0

Views: 520

Answers (1)

Peter Riesz
Peter Riesz

Reputation: 3426

You could use logical AND in your example:

{areaQuestions.map(
  question => <Field
      component={SelectField}
      key={question.area}
      label={question.questionText}
      name={question.area}
      placeholder={question.questionText}
      options={question.questionAnswers}
      validate={question.required && required}
  />
)}

You could also build an array if it gets more complex:

const validate = [];
if(question.required) {
    validate.push(required);
}

return <Field ... validate={validate} />;

Upvotes: 3

Related Questions