Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React PropTypes validation for arrayOf required elements not working properly

The empty array [] passes the following PropTypes definition, even though we state that the string elements are mandatory.

{
    a: React.PropTypes.arrayOf(
        React.PropTypes.string.isRequired
    ).isRequired
}

On the contrary, the empty object {} does not pass the following propTypes definition:

{
    a: React.PropTypes.shape({
        x: PropTypes.string.isRequired
    }).isRequired
}

Array validation seems to be not working correctly. Any ideas?

like image 494
Yavuz Mester Avatar asked Oct 18 '22 02:10

Yavuz Mester


1 Answers

You could utilize the custom validator. I don't believe you can enforce the string.isRequired inside the arrayOf when there are no items.. judging from how the custom validator of an arrayOf works, it seems to invoke the callback on each key. So, if the value has no keys, then no validators would be called.

(Note, this isn't tested)

a: function(props, propName, componentName) {
  var errorCount = 0
  var prop = props[propName]
  // ensure it is an array
  if (typeof prop !== 'array') {
    errorCount++
  }
  // ensure array has items
  else if (prop.length == 0) {
    errorCount++
  }
  // ensure all items are strings
  else {
    for (var i = 0; i < prop.length; i++) {
      if (typeof prop[i] !== 'string') errorCount++
    }
  }
  // throw error
  if (errorCount > 0) {
    return new Error(
      'Invalid prop `' + propName + '` supplied to' +
      ' `' + componentName + '`. Validation failed.'
    );
  }
like image 109
BradByte Avatar answered Oct 21 '22 06:10

BradByte