Search code examples
reactjsdatereact-proptypes

React Prop Validation for Date Strings


How can I validate date strings in the format yyyy/mm/dd?

I know I can use PropTypes.string but it is too loose.


Solution

  • You can basically copy-paste from prop-types documentation using a proper regex:

    yourProp: function(props, propName, componentName) {
      if (!/\d{4}\/\d{2}\/\d{2}/.test(props[propName])) {
        return new Error(
          'Invalid prop `' + propName + '` supplied to' +
          ' `' + componentName + '`. Validation failed.'
        );
      }
    }
    

    Remember, the documentation is your friend: https://www.npmjs.com/package/prop-types