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.

Force "required" prop on a field depending on its form's rules

See original GitHub issue

What

Allow “required” to be set in a rule’s definition instead of form attribute

Why

I’m auto generating my validation rules and would like to keep the validation defined in one place. Having to maintain the “required” attribute on inputs could get out of sync and require extra maintenance.

How

authorizationKey: {
            length: validation.isLengthBetween(8,14),
            oneNumber: validation.hasOneNumber,
            required: true <---
}

Keynotes

It would also be nice if it could maintain the same behavior as the attribute where the other rules for a field are not evaluated if the required rule is not met.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
kettanaitocommented, Aug 8, 2018

@T-Roth I’m glad I could help you.

If I may, there is a slightly lighter version of the same solution you’ve come up with:

const getRequiredProp = (formRules) => {
  return (fieldSelector) => {
    const fieldRules = formRules.getIn(fieldSelector)

    if (fieldRules) {
      const required = fieldRules.get('required')
      return typeof required === 'function'
        ? required()
        : required
    }

    return false
  }
}

const shouldForceRequired = (fieldRecord, context) => {
  const { formRules } = context.form

  return [
    ['type', fieldRecord.type],
    ['name', fieldRecord.name],
  ].some(getRequiredProp(formRules))
}

export default createField({
  ...fieldPresets.input,
  mapPropsToField: ({ fieldRecord, context }) => ({
    ...fieldRecord,
    required: shouldForceRequired(fieldRecord, context),
  })
})(Input)

I am confused why fieldRules returns the instance of ImmutableJS. I think if (fieldRules.get) check is redundant. However, it’s beneficial, since we can use deep key refs by .getIn() and omit unnecessary safety check.

0reactions
T-Rothcommented, Aug 7, 2018

Sorry I didn’t get back to you sooner, your suggestion is working. Thanks for the help.

This is what I quickly came up with in case someone else wants to go this route (typescript):

const isRequiredValue = (value: ()=>boolean) : boolean => {
    const isFunction = typeof(value) === "function"
    if(isFunction) {
        return value() === true;
    } 
    return false;
}

const getRequiredValue = (fieldRules: any) : boolean => {
    if(fieldRules !== undefined 
        && typeof(fieldRules.get) === "function"
        && fieldRules.get("required") !== undefined) {

        return isRequiredValue(fieldRules.get("required"))
    }
    return false;
}

const requiredThroughName = (formRules: any, fieldName: string) => {
    const nameRules = formRules.get("name");
    
    return getRequiredValue(nameRules.get(fieldName));
}

const requiredThroughType = (formRules: any, fieldType: string) => {
    const typeRules = formRules.get("type");
    return getRequiredValue(typeRules.get(fieldType));
}

const shouldForceRequired = (context:any, field: any) => {
    const formRules = context.form.formRules;
    
    const isRequired = (
         requiredThroughName(formRules, field.name)
        || requiredThroughType(formRules, field.type)
    );

    return isRequired
}
  
const fieldOptions = Object.assign({}, fieldPresets.input, {
    mapPropsToField: (args:any) => ({
        ...args.fieldRecord,
        required: shouldForceRequired(args.context, args.fieldRecord)
    })
})
  
export default createField(fieldOptions)(Input)
Read more comments on GitHub >

github_iconTop Results From Across the Web

Client-side form validation - Learn web development | MDN
If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid.
Read more >
React form validation solutions: An ultimate roundup
This roundup is a comprehensive look at some of the most popular solutions for form management and validation in React.
Read more >
Form - Ant Design
High performance Form component with data scope management. Including data collection, verification, and styles.
Read more >
eslint-plugin-react/prop-types.md at master - GitHub
This rule will validate your prop types regardless of how you define them. Rule Details. Examples of incorrect code for this rule: function...
Read more >
Using the HTML5 "required" attribute for a group of checkboxes?
the browsers detects that the "required" field is empty and does not submit the form; instead browser shows a hint asking the user...
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