mobx-react-form
Version:
Reactive MobX Form State Management
216 lines (205 loc) • 7.4 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("_"));
else if(typeof define === 'function' && define.amd)
define(["_"], factory);
else if(typeof exports === 'object')
exports["MobxReactFormValidatorSVK"] = factory(require("_"));
else
root["MobxReactFormValidatorSVK"] = factory(root["_"]);
})(self, (__WEBPACK_EXTERNAL_MODULE_lodash__) => {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/validators/SVK.ts":
/*!*******************************!*\
!*** ./src/validators/SVK.ts ***!
\*******************************/
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const lodash_1 = __importDefault(__webpack_require__(/*! lodash */ "lodash"));
const isPromise = (obj) => !!obj &&
typeof obj.then === "function" &&
(typeof obj === "object" || typeof obj === "function");
/**
Schema Validation Keywords
const plugins = {
svk: svk({
package: ajv,
extend: callback,
}),
};
*/
class SVK {
constructor({ config, state = null, promises = [], }) {
Object.defineProperty(this, "promises", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "config", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "state", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "extend", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "validator", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
Object.defineProperty(this, "schema", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
this.state = state;
this.promises = promises;
this.extend = config === null || config === void 0 ? void 0 : config.extend;
this.schema = config.schema;
this.initAJV(config);
}
extendOptions(options = {}) {
return Object.assign(options, {
errorDataPath: "property",
allErrors: true,
coerceTypes: true,
v5: true,
});
}
initAJV(config) {
// get ajv package
const ajv = config.package;
// create ajv instance
const validator = new ajv(this.extendOptions(config.options));
// extend ajv using "extend" callback
if (typeof this.extend === 'function') {
this.extend({
form: this.state.form,
validator,
});
}
// create ajv validator (compiling rules)
this.validator = validator.compile(this.schema);
}
validate(field) {
const validate = this.validator(field.state.form.validatedValues);
// check if is $async schema
if (isPromise(validate)) {
const $p = validate
.then(() => field.setValidationAsyncData(true))
.catch((err) => err && this.handleAsyncError(field, err.errors))
.then(() => this.executeAsyncValidation(field));
// push the promise into array
this.promises.push($p);
return;
}
// check sync errors
this.handleSyncError(field, this.validator.errors);
}
handleSyncError(field, errors) {
const fieldErrorObj = this.findError(field.path, errors);
// if fieldErrorObj is not undefined, the current field is invalid.
if (lodash_1.default.isUndefined(fieldErrorObj))
return;
// the current field is now invalid
// add additional info to the message
const msg = `${field.label} ${fieldErrorObj.message}`;
// invalidate the current field with message
field.invalidate(msg, false);
}
handleAsyncError(field, errors) {
// find current field error message from ajv errors
const fieldErrorObj = this.findError(field.path, errors);
// if fieldErrorObj is not undefined, the current field is invalid.
if (lodash_1.default.isUndefined(fieldErrorObj))
return;
// the current field is now invalid
// add additional info to the message
const msg = `${field.label} ${fieldErrorObj.message}`;
// set async validation data on the field
field.setValidationAsyncData(false, msg);
}
findError(path, errors) {
return lodash_1.default.find(errors, ({ dataPath }) => {
let $dataPath;
$dataPath = lodash_1.default.trimStart(dataPath, ".");
$dataPath = lodash_1.default.replace($dataPath, "]", "");
$dataPath = lodash_1.default.replace($dataPath, "[", ".");
return lodash_1.default.includes($dataPath, path);
});
}
executeAsyncValidation(field) {
if (field.validationAsyncData.valid === false) {
field.invalidate(field.validationAsyncData.message, false, true);
}
}
}
exports["default"] = (config) => ({
class: SVK,
config,
});
/***/ }),
/***/ "lodash":
/*!********************!*\
!*** external "_" ***!
\********************/
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_MODULE_lodash__;
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __webpack_require__("./src/validators/SVK.ts");
/******/
/******/ return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=MobxReactFormValidatorSVK.umd.js.map