This repository was archived by the owner on Sep 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 349
This repository was archived by the owner on Sep 1, 2024. It is now read-only.
Documentation about custom validators calling other validators #74
Copy link
Copy link
Open
Description
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 ?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels