Search code examples
reactjsreact-proptypes

With React prop-types is it possible to validate on whether a string contains something?


I have a button component with a colour prop. Colour prop can be either 'primary', 'secondary' or a hex colour e.g '#0000ff'. Of course colour: PropTypes.string will do but ideally I need to check against random strings. Is something like below possible?

Button.propTypes = {
  colour: PropTypes.oneOf(['primary', 'secondary', PropTypes.string.includes('#')]),
};

Or a function to check that string is up to 7 characters long with first character being '#'?


Solution

  • You can write your own validator.

    See the React docs for more details.


    Button.propTypes = {
      colour: function(props, propName, componentName) {
        if (props[propName] !== 'primary' &&
            props[propName] !== 'secondary' &&
            !/^#[0-9a-fA-F]{6}$/.test(props[propName])) {
          return new Error(
            'Invalid prop `' + propName + '` supplied to' +
            ' `' + componentName + '`. Must be a valid color code.'
          );
        }
      }
    }