Dynamic check validation with redux form

670 views Asked by At

I need to check a field depending on a other other field with redux form and React-JS. The form is generated dynamically from a object.

For example I have two fields on my Form. A checkbox pickup_allowed and a zip text.

The zip text is mandatory and visible only if pickup_allowed is checked. How can I check a field depending on a other field and render visible or not with redux form and React JS ?

Code :

const sellingFormFieldDescription = [
                {key: 'pickup_allowed',
                 type: 'checkbox',
                 checkRules: {
                       mandatory: false
                 } },
                {
                key: 'zip_code',
                type: 'integer',
                checkRules: {
                    minValue: 1,
                    maxValue: 99999,
                    maxLength: 5,
                    mandatoryAndVisibleIf : {  key:'pickup_allowed', checked: true}
                }]



const minValue = min => value =>
  value && value > min && `Must be greater than ${ min }` || undefined;
const maxValue = max => value =>
  value && value > max && `Must be greater than ${ max }` || undefined;
const maxLength = max => value =>
  value && value.length > max && `Must be longer than ${ max }` || undefined;
const mandatory = isMandatory => value =>
  isMandatory && value && undefined || 'Mandatory';

const rules = { minValue, maxValue, maxLength, mandatory };

const applyRules = checkRules => {
  let validations = [];
  for(let ruleName in checkRules) {
    let ruleFunc = rules[ruleName]
    if(ruleFunc) {
      validations.push(ruleFunc(checkRules[ruleName]))
    }
  }
  return validations;
}


class SellingFormFast extends Component {
  render() {
    { sellingFormFieldDescription.map((field,i) => {
      const validate = applyRules(field.checkRules);
      if(field.type === 'checkbox' ){
        return <Field name={field.key} key={i} component={renderCheckbox} validate={validate} />
      } else if (field.type === 'integer') {
        return <Field name={field.key} key={i} component={renderField} validate={validate}/>
      }});
    }
  }
}

export default reduxForm({form: 'sellling_form_fast'})(SellingFormFast)
0

There are 0 answers