React.PropTypes.number float with min and max

眉间皱痕 提交于 2019-12-05 19:39:41

You can use Custom Validation.

completed: function(props, propName, componentName) {
   if(props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid');
   }
}

By writing a Custom Props Validator, u can achieve this. try this:

num: function(props, propName, componentName) {
    if(typeof props[propName] != 'number'){
      return new Error ('Invalid type of `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }else if (props[propName] < MIN || props[propName] > MAX) {
      return new Error('Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
    }
},

The CustomProp just like the Docs said:

completed: (props, propName, componentName) => 
             (props[propName] < MIN || props[propName] > MAX) && new Error('Invalid');

I know this is an old post, but I thought I would share as I ran into this issue as well. All of the other answers address how to use this functionality for a single prop, but if you need this for multiple props, then creating a reusable PropType might be a better solution.

// Allow min/max values to be passed to PropType validator
export default const numberBetween = (min, max) => {
    // Return CustomProp to be executed
    return (props, propName, componentName) => {
        const prop = props[propName];
        if(typeof prop !== 'number' || prop < min || prop > max) {
            return new Error(`Prop ${propName} must be a number between ${min} and ${max} on ${componentName}`);
        }
    }
}

It is then used like this:

completed: numberBetween(1, 10)

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!