mobx-react-form
Version:
Reactive MobX Form State Management
99 lines • 3.47 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
class YUP {
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: void 0
});
Object.defineProperty(this, "state", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "extend", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "validator", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "schema", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.state = state;
this.promises = promises;
this.extend = config === null || config === void 0 ? void 0 : config.extend;
this.validator = config.package;
this.schema = config.schema(this.validator);
this.extendValidator();
}
// Metodo per estendere il validatore
extendValidator() {
if (typeof this.extend === 'function') {
this.extend({
validator: this.validator,
form: this.state.form,
});
}
}
// Metodo di validazione principale
validate(field) {
const fieldValidationPromise = this.createValidationPromise(field);
this.promises.push(fieldValidationPromise);
}
// Creazione della promise per la validazione
createValidationPromise(field) {
return new Promise((resolve) => {
this.schema
.validateAt(field.path, this.state.form.values(), { strict: true })
.then(() => this.handleAsyncPasses(field, resolve))
.catch((error) => this.handleAsyncFails(field, resolve, error));
});
}
// Gestione dei successi della validazione asincrona
handleAsyncPasses(field, resolve) {
field.setValidationAsyncData(true);
resolve();
}
// Gestione dei fallimenti della validazione asincrona
handleAsyncFails(field, resolve, error) {
var _a, _b;
// Yup a volte restituisce errori senza path (es. array vuoti)
const isSameField = error.path === field.path || error.path === undefined;
if (isSameField) {
const message = (_a = error.message) === null || _a === void 0 ? void 0 : _a.replace((_b = error.path) !== null && _b !== void 0 ? _b : field.path, field.label);
field.setValidationAsyncData(false, message);
this.executeAsyncValidation(field);
}
resolve(undefined);
}
// Esecuzione della validazione asincrona
executeAsyncValidation(field) {
if (field.validationAsyncData.valid === false) {
field.invalidate(field.validationAsyncData.message, false, true);
}
}
}
exports.default = (config) => ({
class: (YUP),
config,
});
//# sourceMappingURL=YUP.js.map
;