Reputation: 833
How can I validate date strings in the format yyyy/mm/dd
?
I know I can use PropTypes.string
but it is too loose.
Upvotes: 2
Views: 4112
Reputation: 59491
I would advise against validating formatting with PropTypes
, since it is primarily meant for type checking of props.
Since PropTypes
is only useful during runtime (i.e it won't generate warnings during compilation), you could instead do something like:
if (!/\d{4}\/\d{2}\/\d{2}/.test(this.props.date) && (!process.env.NODE_ENV || process.env.NODE_ENV === 'development')) {
console.warn('Warning: Invalid format for date prop');
}
You could put this in your constructor, for example.
That being said, you could still use PropTypes
if you really want by passing a custom function. I was going to write a solution, but 0xc14m1z beat me to it :)
Here's a previous answer of mine that you might find useful: https://stackoverflow.com/a/40302064/2030321
Upvotes: 2
Reputation: 3725
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
Upvotes: 3
Reputation: 334
Why don't you use Date.parse()
?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Upvotes: 2