Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Created August 6, 2019 15:14
Show Gist options
  • Save dmmulroy/91ae886d81b49c050e96dfe225d5e2e7 to your computer and use it in GitHub Desktop.
Save dmmulroy/91ae886d81b49c050e96dfe225d5e2e7 to your computer and use it in GitHub Desktop.
const withIsRequired = validatorFn => {
const _customPropValidator = (isRequired = false) => (props, propName, componentName) => {
const value = props[propName];
if (value == null) {
if (isRequired) {
return new Error(`Required \`${propName}\` was not specified in \`${componentName}\`.`);
}
return undefined;
}
return validatorFn(props, propName, componentName);
};
const customPropValidator = _customPropValidator();
customPropValidator.isRequired = _customPropValidator(true);
return customPropValidator;
};
@dmmulroy
Copy link
Author

dmmulroy commented Aug 6, 2019

Example:

const color = withIsRequired((props, propName, componentName) => {
  const value = props[propName];const isColor = colorValue => {
    // hex, rgb, rgba, hsl, hsla
    const colorFlag = /^#(?:[A-Fa-f0-9]{3}){1,2}$/i.test(colorValue);
    return colorFlag;
  };if (!isColor(value)) {
    return new Error(
      `\`${value}\` is not a correct color format for \`${propName}\`
      in \`${componentName}\`. Must be in hex, rgb, rgba, hsl, or hsla format.`
    );
  }
  return undefined;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment