Skip to content

Instantly share code, notes, and snippets.

@joeynguyen
Last active August 22, 2019 16:46
Show Gist options
  • Save joeynguyen/4e349b9f2dd7c6ea19d8b9c1833b72ed to your computer and use it in GitHub Desktop.
Save joeynguyen/4e349b9f2dd7c6ea19d8b9c1833b72ed to your computer and use it in GitHub Desktop.
custom PropTypes validator for Moment object
import moment from 'moment'; // tested using v2.24.0
// custom PropType validator per example at
// https://github.com/facebook/prop-types/blob/v15.7.2/README.md#usage
export function isMomentPropType(props, propName, componentName) {
if (!moment.isMoment(props[propName])) {
return new Error(
`Invalid prop ${propName} supplied to ` +
`${componentName} is not a Moment object. Validation failed.`
);
}
return null;
}
isMomentPropType.isRequired = () => null;
// Jest test
import PropTypes from 'prop-types'; // tested using v15.7.2
import moment from 'moment'; // tested using v2.24.0
import { isMomentPropType } from './index';
// Test using example from
// // https://github.com/facebook/prop-types/blob/v15.7.2/README.md#proptypescheckproptypes
test('isMomentPropType validates valid moment object', () => {
// define your prop validations
const myPropTypes = {
momentDate: isMomentPropType.isRequired,
};
// pass props values
const props = {
momentDate: moment(),
};
// validate
PropTypes.checkPropTypes(myPropTypes, props, 'momentDate', 'MyComponent');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment