UNPKG

@codice-progressio/input-validaciones

Version:
414 lines (407 loc) 16.2 kB
import * as i0 from '@angular/core'; import { Injectable, Component, Input, NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; class InputValidacionesService { /** * Si el campo tiene valores invalidos retorna false ( Esto sirve para * bootstrap * * @param {AbstractControl} campo El campo que se quiere comprobar * @returns {boolean} * @memberof InputValidacionesService */ invalid(campo) { return campo.touched && campo.invalid; } /** * * Si el campo tiene valores validos retorna true * * @param {AbstractControl} campo El campo que se quiere comprobar * @returns {boolean} * @memberof InputValidacionesService */ valid(campo) { return campo.touched && campo.valid; } /** *Valida una url * * @param {AbstractControl} campo * @returns {*} * @memberof InputValidacionesService */ urlValidator(campo, mensaje = 'La url no es valida') { if (campo.pristine) { return null; } // tslint:disable-next-line:max-line-length const URL_REGEXP = /^(http?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/; campo.markAsTouched(); if (URL_REGEXP.test(campo.value)) { return null; } return { invalidUrl: true, url: campo.value, mensaje, }; } /** *Valida que dos campos llamados password y confirm coincidan. * * @param {FormGroup} group El formulario completo * @returns {*} * @memberof InputValidacionesService */ matchPassword(group, mensaje = 'Las contraseñas no coinciden') { const password = group.controls.password; const confirm = group.controls.confirm; if (password.pristine || confirm.pristine) { return null; } group.markAsTouched(); if (password.value === confirm.value) { return null; } return { invalidPassword: true, mensaje, }; } numberValidator(campo, mensaje = 'No es un numero valido') { if (campo.pristine) { return null; } const NUMBER_REGEXP = /^\-?[0-9]+(?:\.[0-9]+)?$/; campo.markAsTouched(); if (NUMBER_REGEXP.test(campo.value)) { return null; } return { invalidNumber: true, mensaje, }; } /** *Valida que solo sean numeros. No lo debes de llamar como funcion, si no como un tipo callback. * * @param {*} campo * @returns {*} * @memberof ValidacionesService */ onlyIntegers(campo, mensaje = 'Solo se permiten números enteteros') { if (campo.pristine) { return null; } campo.markAsTouched(); const INTEGERS_REGEXP = /^[0-9]+$/; if (INTEGERS_REGEXP.test(campo.value)) { return null; } return { notInteger: true, mensaje }; } ssnValidator(ssn) { if (ssn.pristine) { return null; } const SSN_REGEXP = /^(?!219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$/; ssn.markAsTouched(); if (SSN_REGEXP.test(ssn.value)) { return null; } return { invalidSsn: true, }; } // Validates US phone numbers phoneValidator(number) { if (number.pristine) { return null; } const PHONE_REGEXP = /^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$/; number.markAsTouched(); if (PHONE_REGEXP.test(number.value)) { return null; } return { invalidNumber: true, }; } // Validates zip codes zipCodeValidator(zip) { if (zip.pristine) { return null; } const ZIP_REGEXP = /^[0-9]{5}(?:-[0-9]{4})?$/; zip.markAsTouched(); if (ZIP_REGEXP.test(zip.value)) { return null; } return { invalidZip: true, }; } /** *Valida un registro federal del contribuyente Mexicano * * @param {AbstractControl} campo * @param {string} [mensaje='RFC invalido'] * @returns {*} * @memberof InputValidacionesService */ rfc(campo, mensaje = 'RFC invalido') { let _rfc_pattern_pm = '^(([A-ZÑ&]{3})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{3})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{3})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{3})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$'; // patron del RFC, persona fisica let _rfc_pattern_pf = '^(([A-ZÑ&]{4})([0-9]{2})([0][13578]|[1][02])(([0][1-9]|[12][\\d])|[3][01])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{4})([0-9]{2})([0][13456789]|[1][012])(([0][1-9]|[12][\\d])|[3][0])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{4})([02468][048]|[13579][26])[0][2]([0][1-9]|[12][\\d])([A-Z0-9]{3}))|' + '(([A-ZÑ&]{4})([0-9]{2})[0][2]([0][1-9]|[1][0-9]|[2][0-8])([A-Z0-9]{3}))$'; let error = { general: { mensaje } }; if (!campo.value) return null; if (campo.value.match(_rfc_pattern_pm) || campo.value.match(_rfc_pattern_pf)) { let r = campo.value.length; if (r > 11 && r < 14) return null; } return error; } /** *Valida la estructura de una CURP Mexicana * * @param {AbstractControl} campo * @param {string} [mensaje='CURP invalida'] * @returns * @memberof InputValidacionesService */ curp(campo, mensaje = 'CURP invalida') { let curp_pattern = /^([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)$/; let error = { general: { mensaje } }; if (!campo.value) return null; if (campo.value.match(curp_pattern)) { if (campo.value.length == 18) return null; } return error; } /** * Valida el formato de un numero de seguridad social Mexicano (NSS) * * @param {AbstractControl} campo * @param {string} [mensaje='Numero de seguridad no valido'] * @returns * @memberof InputValidacionesService */ nss(campo, mensaje = 'Numero de seguridad no valido') { let NSS_pattern = /^(\d{2})(\d{2})(\d{2})\d{5}$/; let error = { general: { mensaje } }; if (!campo.value) return null; if (campo.value.match(NSS_pattern)) { if (campo.value.length === 11) return null; } return error; } fechaMenorQue(campoFecha1, campoFecha2, campoValidador = { general: { mensaje: 'Se han encontrado fechas invalidas', }, }) { return (c) => { const date1 = c.get(campoFecha1).value; const date2 = c.get(campoFecha2).value; if (date1 !== null && date2 !== null && date1 > date2) { c.get(campoFecha1).setErrors({ general: { mensaje: 'Esta fecha tiene que ser menor que la de finalizacion', }, }); c.get(campoFecha2).setErrors({ general: { mensaje: 'Esta fecha tiene que ser mayor que la de inicio', }, }); return campoValidador; } c.get(campoFecha1).updateValueAndValidity({ onlySelf: true }); c.get(campoFecha2).updateValueAndValidity({ onlySelf: true }); return null; }; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesService, providedIn: 'root' }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); class InputValidacionesComponent { _campo = null; mensaje = {}; /** * El control con el que se haran las comprobaciones. * * @type {AbstractControl} * @memberof ValidacionInputsComponent */ set campo(value) { this._campo = value; if (value) { this.mensaje = { required: () => { return `Este campo es obligatorio`; }, min: this.min.bind(this), max: this.max.bind(this), notInteger: () => { return `Se necesita un número entero positivo`; }, invalidNumber: () => { return `No es un número válido`; }, tamanoMinimo: this.tamanoMinimo.bind(this), minlength: this.minlength.bind(this), maxlength: this.maxlength.bind(this), general: this.general.bind(this), email: () => { return "Correo no valido"; }, "Mask error": () => "Hay un error en el formato (mask)", }; } } get campo() { return this._campo; } /** * Un texto especial que se quiera mostrar. Este no se valida. * * @type {string} * @memberof ValidacionInputsComponent */ especial = null; /** * Define si se salta la validacion del touch para mostrar * siempre la validacion aunque el usuario no interactue con el * control. * * @type {boolean} * @memberof ValidacionInputsComponent */ directo = false; debug = false; constructor() { } ngOnInit() { } min() { return `El valor mínimo permitido es ${this.cge("min").min}`; } max() { return `El máximo permitido es ${this.cge("max").max}`; } tamanoMinimo() { let cantidad = this.cge("tamanoMinimo").minimo > 1 ? "" : "un "; let campo = this.cge("tamanoMinimo").minimo > 1 ? "campos" : "campo"; return `Debes seleccionar por lo menos ${cantidad} ${campo}`; } minlength() { let campo = this.cge("minlength"); let cantidadCar = campo.requiredLength; let faltan = cantidadCar - campo.actualLength; let conjuncion = cantidadCar > 1 ? cantidadCar : "un "; let caracteres = cantidadCar > 1 ? "caracteres" : "caracter"; return `Debes escribir por lo menos ${conjuncion} ${caracteres}. (Faltan ${faltan})`; } maxlength() { let campo = this.cge("maxlength"); let cantidadCar = campo.requiredLength; let sobran = campo.actualLength - cantidadCar; let conjuncion = cantidadCar > 1 ? cantidadCar : "un "; let caracteres = cantidadCar > 1 ? "caracteres" : "caracter"; return `El máximo es ${conjuncion} ${caracteres}. (Sobran ${sobran})`; } general() { return this.cge("general").mensaje; } cge(a) { return this.campo.getError(a); } che(a) { if (!this.campo) return false; return this.campo.hasError(a); } listaDeErrores() { if (!this.campo) return []; if (!this.campo.errors) return []; return Object.keys(this.campo.errors); } /** * Comprueba si el campo a sido tocado si directo no a sido * puesto como true. Si ha sido puesto como true retorna true * directamete. * * @returns True si ha sido tocado o directo esta como true. * @memberof ValidacionInputsComponent */ touched() { if (this.directo) return true; if (this.campo) { return this.campo.touched; } return false; } obtenerMensaje(key) { if (this.mensaje.hasOwnProperty(key)) return this.mensaje[key](); return `Mensaje no definido para ${key}`; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.1", type: InputValidacionesComponent, selector: "codice-validaciones", inputs: { campo: "campo", especial: "especial", directo: "directo", debug: "debug" }, ngImport: i0, template: "<!-- <ng-container *ngIf=\"campo && touched()\">\r\n <ng-container *ngFor=\"let error of listaDeErrores()\">\r\n <div class=\"text-danger \">\r\n <i class=\"fas fa-times\"></i>\r\n {{ obtenerMensaje(error) }}\r\n </div>\r\n </ng-container>\r\n\r\n <pre *ngIf=\"debug\">{{ campo?.errors | json }}</pre>\r\n</ng-container>\r\n\r\n<ng-container *ngIf=\"especial\">\r\n <span class=\"form-text text-danger\">\r\n <i class=\"fas fa-times animated tada\"></i> {{ especial }}.</span\r\n >\r\n</ng-container> -->\r\n" }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesComponent, decorators: [{ type: Component, args: [{ selector: "codice-validaciones", template: "<!-- <ng-container *ngIf=\"campo && touched()\">\r\n <ng-container *ngFor=\"let error of listaDeErrores()\">\r\n <div class=\"text-danger \">\r\n <i class=\"fas fa-times\"></i>\r\n {{ obtenerMensaje(error) }}\r\n </div>\r\n </ng-container>\r\n\r\n <pre *ngIf=\"debug\">{{ campo?.errors | json }}</pre>\r\n</ng-container>\r\n\r\n<ng-container *ngIf=\"especial\">\r\n <span class=\"form-text text-danger\">\r\n <i class=\"fas fa-times animated tada\"></i> {{ especial }}.</span\r\n >\r\n</ng-container> -->\r\n" }] }], ctorParameters: () => [], propDecorators: { campo: [{ type: Input }], especial: [{ type: Input }], directo: [{ type: Input }], debug: [{ type: Input }] } }); class InputValidacionesModule { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesModule, declarations: [InputValidacionesComponent], imports: [CommonModule], exports: [InputValidacionesComponent] }); static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesModule, imports: [CommonModule] }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.1", ngImport: i0, type: InputValidacionesModule, decorators: [{ type: NgModule, args: [{ declarations: [InputValidacionesComponent], imports: [CommonModule], exports: [InputValidacionesComponent], }] }] }); /* * Public API Surface of input-validaciones */ /** * Generated bundle index. Do not edit. */ export { InputValidacionesComponent, InputValidacionesModule, InputValidacionesService }; //# sourceMappingURL=codice-progressio-input-validaciones.mjs.map