UNPKG

ms-react-reactive-form

Version:

an implementation of the Reactive Form concept in React, supporting Javascript and Typescript

120 lines (119 loc) 4.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class BaseValidator { constructor(passedForm) { this.result = (controls, Model) => { let validity = true; Object.keys(controls).forEach((control) => { Object.keys(controls[control].errors).forEach(error => { if (controls[control].errors[error] !== false) { validity = false; controls[control].validity = false; } }); }); this.form.controls = controls; this.form.validity = validity; this.form.submited = true; let results = {}; if (!Model) { Object.keys(controls).forEach((controlName) => { results[controlName] = controls[controlName].value; }); } return { payload: Model ? new Model(controls) : results, form: this.form }; }; this.form = passedForm; this.analysis(); } analysis() { return new Promise(resolve => { let { controls } = this.form; Object.keys(controls).forEach((item) => { let control = controls[item]; let { requiredValidations, value, errors } = control; if (requiredValidations.required) { if (!value) { errors.required = true; } else { errors.required = false; } } if (requiredValidations.pattern) { const reg = new RegExp(requiredValidations.pattern); if (value) { if (value && !reg.test(value)) { errors.pattern = true; } else { errors.pattern = false; } } else { errors.pattern = false; } } if (requiredValidations.maxLength) { if (value) { if (value.trim(" ").length > requiredValidations.maxLength) { errors.maxLength = true; } else { errors.maxLength = false; } } else { errors.maxLength = false; } } if (requiredValidations.minLength) { if (value) { if (value.trim(" ").length < requiredValidations.minLength) { errors.minLength = true; } else { errors.minLength = false; } } else { errors.minLength = false; } } if (requiredValidations.max) { if (!isNaN(Number(value)) && value !== "") { value = Number(value); if (requiredValidations.max < value) { errors.max = true; } else { errors.max = false; } } else { errors.max = false; } } if (requiredValidations.min) { if (!isNaN(Number(value)) && value !== "") { value = Number(value); if (requiredValidations.min > value) { errors.min = true; } else { errors.min = false; } } else { errors.min = false; } } }); return resolve(controls); }); } } exports.default = BaseValidator;