Skip to content
This repository was archived by the owner on Sep 1, 2024. It is now read-only.
This repository was archived by the owner on Sep 1, 2024. It is now read-only.

Documentation about custom validators calling other validators #74

@amangeot

Description

@amangeot

Hello,
I am wondering how to implement a custom validator which checks the type of an object.

The documentation is very clear for custom validators which do not call other validators, but it is quite unclear how validators should be called from custom validators. I have tried using PropTypes.checkPropTypes but couldn't make it happen.


Here is a solution that seems to be working:

// const customPropTypes = {...}

function (props, propName, componentName, ...rest) {
  if (props[propName]) {
    const { type } = props[propName]

    if (!type) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Missing type.`)
    } else if (Object.keys(customPropTypes).indexOf(type) === -1) {
      return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. Unhandled type: ${type}.`)
    }

    return customPropTypes[type](props, propName, componentName, ...rest)
  }

  return null
}

Another challenge is to make the custom validator chainable in order to chain it with .isRequired. A blog post suggested to implement it this way:

const ANONYMOUS = '<<anonymous>>'

export default function createChainableTypeChecker (validate) {
  function checkType (isRequired, props, propName, componentName, ...rest) {
    componentName = componentName || ANONYMOUS

    if (props[propName] == null) {
      // var locationName = ReactPropTypeLocationNames[location]
      if (isRequired) {
        // return new Error(`Required ${locationName} \`${propName}\` was not specified in \`${componentName}\`.`)
        return new Error(`Required \`${propName}\` was not specified in \`${componentName}\`.`)
      }
      return null
    } else {
      return validate(props, propName, componentName, ...rest)
    }
  }

  var chainedCheckType = checkType.bind(null, false)
  chainedCheckType.isRequired = checkType.bind(null, true)

  return chainedCheckType
}

I commented out the part related to locationName as I could not figure out where ReactPropTypeLocationNames


Is it the way to solve to implement custom validators which call other validators ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions