@gdimx/ngx-input-validator
Version:
Libreriía de validaciones reutilizables para formularios en angular
128 lines (108 loc) • 5.68 kB
text/typescript
export class NgxInputValidator {
// Requiere que el campo no se encuentre vacío
static required(control: any): { [key: string]: any } | null {
return control.value?.toString().trim() ? null : { required: true };
}
// Valida si el campo es un correo electrónico
static email(control: any): { [ key: string]: any} | null {
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return regex.test(control.value) ? null : { email: true };
}
// Valida que solo haya letras
static alpha(control: any): { [key: string]: any } | null {
const regex = /^[a-zA-ZÀ-ÿ\u00f1\u00d1\s]*$/;
return regex.test(control.value) ? null : { alpha: true }
}
// Valida alphanuméricos
static alphaNumeric(control: any): { [key: string]: any } | null {
const regex = /^[a-zA-Z0-9]*$/;
return regex.test(control.value) ? null : { alphaNumeric: true }
}
// Valida solo números
static numeric(control: any): { [key: string]: any } | null {
const regex = /^\d+$/;
return regex.test(control.value) ? null : { numeric: true }
}
// Valida mínima longitud
static minLength( min: number){
return (control: any): {[key: string]: any} | null => {
return control.value?.length >= min ? null : { minLength: { requiredLength: min } };
}
}
// Valida máxima longitud
static maxLength( max: number){
return (control: any): {[key: string]: any} | null => {
return control.value?.length <= max ? null : { maxLength: { requiredLength: max } };
}
}
// Valida caracteres permitidos personalizados
static allowedCharacters(regex: RegExp, errorKey = 'invalidCharacters'){
return (control: any): {[key: string]: any} | null => {
return regex.test(control.value) ? null : { [errorKey]: true };
};
}
static noSpaces(control: any): { [key: string]: any } | null {
const regex = /^\S*$/;
return regex.test(control.value) ? null : { noSpaces: true };
}
static onlyUppercase(control: any): { [key: string]: any } | null {
const regex = /^[A-Z0-9\s]*$/;
return regex.test(control.value) ? null : { onlyUppercase: true };
}
static onlyLowercase(control: any): { [key: string]: any } | null {
const regex = /^[a-z0-9\s]*$/;
return regex.test(control.value) ? null : { onlyLowercase: true };
}
static disallowedCharacters(regex: RegExp, errorKey = 'forbiddenCharacters') {
return (control: any): { [key: string]: any } | null => {
return regex.test(control.value) ? { [errorKey]: true } : null;
};
}
static decimal(control: any): { [key: string]: any } | null {
const regex = /^\d+(\.\d+)?$/;
return regex.test(control.value) ? null : { decimal: true };
}
static rfc(control: any): { [key: string]: any } | null {
const regex = /^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/;
return regex.test(control.value?.toUpperCase()) ? null : { rfc: true };
}
static curp(control: any): { [key: string]: any } | null {
const regex = /^[A-Z][AEIOUX][A-Z]{2}\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])[HM](AS|BC|BS|CC|CL|CM|CS|CH|DF|DG|GT|GR|HG|JC|MC|MN|MS|NT|NL|OC|PL|QT|QR|SP|SL|SR|TC|TS|TL|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d]\d$/;
return regex.test(control.value?.toUpperCase()) ? null : { curp: true };
}
// Mensajes de error centralizados
static getErrorMessage(control: any): string{
if(!control || !control.errors) return '';
const errors = control.errors;
if (errors.required ) return 'Este campo es obligatorio';
if (errors.email ) return 'Correo electrónico no válido';
if (errors.alpha ) return 'Solo letras permitidas';
if (errors.alphaNumeric ) return 'Solo caracteres alfanuméricos permitidos';
if (errors.numeric ) return 'Solo números permitidos';
if (errors.minLength ) return `Mínimo ${errors.minLength.requiredLength} caracteres`;
if (errors.maxLength ) return `Máximo ${errors.maxLength.requiredLength} caracteres`;
if (errors.invalidCharacters ) return 'Contiene caracteres no permitidos';
if (errors.noSpaces ) return 'No se permiten espacios';
if (errors.onlyUppercase ) return 'Solo mayúsculas permitidas';
if (errors.onlyLowercase ) return 'Solo minúsculas permitidas';
if (errors.invalidCharacters ) return 'Contiene caracteres no permitidos';
if (errors.forbiddenCharacters ) return 'Contiene caracteres prohibidos';
if (errors.decimal ) return 'Debe ser un número decimal';
if (errors.rfc ) return 'RFC inválido';
if (errors.curp ) return 'CURP inválido';
return 'Campo invalido';
}
// Devuelve en un solo string todos los mensajes del error del formulario
static getAllFormErrors(form: any): string {
if(!form || typeof form !== 'object') return '';
const messages: string[] = [];
Object.keys(form.controls).forEach(key => {
const control = form.get(key);
const message = this.getErrorMessage(control);
if(message){
messages.push(`• ${message}`);
}
});
return messages.join('\n');
}
}