question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add dynamic rules validations to dynamic form

See original GitHub issue

I want to generate a dynamic forms with dynamic validations.

For example : fields description and check rules are stored on a array like this

const sellingFormFieldDescription = [
                {key: 'state',
                 type: 'shared',
                 checkRules: {
                       maxLength: 255,
                       mandatory: true,
                 } },
                {
                key: 'sellingPrice',
                label: 'Price',
                type: 'decimal',
                checkRules: {
                    minValue: 1,
                    maxValue: 10000,
                    maxLength: 10,
                    mandatory: true,
                }]

With this array I want to generate two fields ( state and price ) on a form with validation rules. For sellingPrice field I need to check if the user has filled the value, and the value between 1 and 10000 and length not > 10) How I can do this ?

My code :

render() {
   { sellingFormFieldDescription.map((field,i) =>
                    if(field.type === 'shared' ){
                         return <Field name={field.key} key={i} component={renderSelect} />
                    } else if (field.type === 'decimal') {
                          return <Field name={field.key} key={i} component={renderField}  />
                    });
}}

const validate = formProps => {
    const errors = {}
    return errors
}

SellingFormFast = reduxForm({
    form: 'sellling_form_fast',  // a unique identifier for this form
    validate

})(SellingFormFast)

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
kevinzwhuangcommented, Jan 6, 2017

I think Field-level validations might work well for you, given your modular approach. Instead of handling every case in the validate option for reduxForm, this will allow you to selectively validate based on what options you provide from your sellingFormFieldDescription object.

You can read more about this here: http://redux-form.com/6.4.3/examples/fieldLevelValidation/

Basically what you can do is compose an array of validation rules for your field in the validate prop for Field. So one of your Field’s might look like:

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;
//......
return <Field {...otherMainFieldProps} validate={[maxValue(5), maxLength(10)]} />

Another improvement on this for your use case might be instead of explicitly declaring which rules are applied to the field, applying them based on the checkRules object of your items in sellingFormFieldDescription.

Here’s an improved example that’s slightly more complicated than the simple example in the documentation, but it might suit your needs better:

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { renderSelect, renderField } from 'somewhereElseInYourApp';

const sellingFormFieldDescription = [
// ! Important !
// the checkRules keys will be the same name as the rules functions we define below!
  {
    key: 'state',
    type: 'shared',
    checkRules: {
      maxLength: 255,
      mandatory: true,
    } },
  {
    key: 'sellingPrice',
    label: 'Price',
    type: 'decimal',
    checkRules: {
      minValue: 1,
      maxValue: 10000,
      maxLength: 10,
      mandatory: true,
    }
  }
]

// Compose your field-level validations the way you want to here:
// For a basic example, go to
// http://redux-form.com/6.4.3/examples/fieldLevelValidation/
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]
    // check if there is a valid validation function for this rule name
    if(ruleFunc) {
      // Push the generated validation to the field-level validations array
      validations.push(ruleFunc(checkRules[ruleName]))
    }
  }
  return validations;
}


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

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

Let me know if this helps or if you have any questions @KrifaYounes

0reactions
lock[bot]commented, Jul 11, 2018

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dynamic Validation in Angular Dynamic Forms | by Ajay Ojha
The bio dynamic FormControl should be validate based upon custom business logic; If the isAuthor value is true then the user can enter...
Read more >
Three Ways to Dynamically Alter your Form Validation in ...
Dynamically Add Validators ​​ The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB...
Read more >
Angular - Dynamically add/remove validators - Stack Overflow
I am using the below code to dynamically add/remove the Validators.required . However, it clears the existing Validators.maxLength validator. if ...
Read more >
Building dynamic forms - Angular
Develop a component to create form controls dynamically. The form you create uses input validation ... You can specify default values and validation...
Read more >
Adding dynamic field - FormValidation
This example demonstrates a sample scenario where you have to solve validating dynamic fields problem. Before going to the details, there are some...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found