UNPKG

react-schema

Version:

Use react like PropTypes for generic object validation.

60 lines (46 loc) 2.08 kB
/** * A helper object for validating a set of PropTypes. */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Validator = (function () { function Validator() { var propTypes = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, Validator); this.propTypes = propTypes; } /** * Validates the given properties. * @param props: An object of properties to validate. * @param componentName: Optional. The name of the component being validated. * Used in error message. * @returns results object. */ _createClass(Validator, [{ key: "validate", value: function validate(props, componentName) { var _this = this; if (props === undefined) props = {}; var result = { isValid: true }; Object.keys(this.propTypes).forEach(function (key) { var validator = _this.propTypes[key]; var error = validator(props, key, componentName); if (error !== null) { result.isValid = false; result.errors = result.errors || {}; result.errors[key] = error; } }); return result; } }]); return Validator; })(); exports["default"] = function (propType) { return new Validator(propType); }; module.exports = exports["default"];