5

I am trying to do propTypes validation for of the array prop within my component. My propTypes validation looks something like this

Foo.propTypes = {
 columns: PropTypes.arrayOf(
    PropTypes.shape({
      identifier: PropTypes.string,
      displayName: PropTypes.string,
      type: PropTypes.string,
      align: PropTypes.oneOf(['right', 'left', 'center']),
      sort: PropTypes.bool
    })
  )
}

Now I want to extend this validation with custom validation, by validating that only one value within columns array for sort property should be true

One option I have is to write the custom validation for whole columns array which would do PropTypes.arrayOf and PropTypes.shape validations and then do sort validation and throw error or null

But I don't want to do rework and want to utilize the inbuilt React.PropTypes to do all the validation and then add my custom validation

2 Answers 2

6

You can utilize PropTypes package within custom validator as well. So solved my issue with following code

Foo.propTypes = {
 columns: function(propValue, key, componentName, location, propFullName) {
    PropTypes.arrayOf(
      PropTypes.shape({
        identifier: PropTypes.string,
        displayName: PropTypes.string,
        type: PropTypes.string,
        align: PropTypes.oneOf(['right', 'left', 'center']),
        sort: PropTypes.bool
      })
    );
    if (propValue.columns.filter(i => i.sort === true).length > 1) {
      return new Error(
        `Invalid prop ${propFullName} supplied to ${componentName}. Only single object can have sort value as true`
      );
    }
    return null;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

prop-types is for runtime type checking, what you are trying to accomplish falls outside of that realm and is more like data validation. I wouldn't recommend using prop-types for this, even if it were possible.

I especially would warn against this because prop-types only warns in development. If your data is invalid, I'd imagine you'd want more of a consequence than that, like unsetting sort from all but one column, or displaying something to your user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.