theseboys
theseboys

Reputation: 537

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 '#'?

Upvotes: 2

Views: 1118

Answers (1)

TimoStaudinger
TimoStaudinger

Reputation: 42460

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.'
      );
    }
  }
}

Upvotes: 4

Related Questions