UNPKG

@gdimx/validateform

Version:

Libreria de validaciones para campos

189 lines (188 loc) 7.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.required = required; exports.minLengthValid = minLengthValid; exports.maxLengthValid = maxLengthValid; exports.email = email; exports.isNumber = isNumber; exports.allowedCharacters = allowedCharacters; exports.disallowedCharacters = disallowedCharacters; exports.phone = phone; exports.date = date; exports.isCapitalLetter = isCapitalLetter; exports.isLowerCase = isLowerCase; exports.isBoth = isBoth; exports.allowsSpaces = allowsSpaces; exports.allowLineBreaks = allowLineBreaks; exports.alphaNumeric = alphaNumeric; exports.alpha = alpha; exports.decimal = decimal; exports.applyValidationOnEvent = applyValidationOnEvent; // Valida si el campo no está vacío function required(value) { // Si el valor es booleano, lo tratamos como falso if (typeof value === 'boolean') { return false; } // Convierte caulquier tipo de cadena y luego valida return String(value).trim() !== ''; } // Valida si el campo tiene al menos una longitud mínima function minLengthValid(value, minLength) { return value.length >= minLength; } // Valida si el campo tiene una longitud Máxima function maxLengthValid(value, maxLength) { return value.length <= maxLength; } // Valida si el campo es un correo electrónico válido function email(value) { const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; return regex.test(value); } // Valida si el campo es un número function isNumber(value) { const regex = /^[0-9]+$/; return regex.test(value); } // Valida si el campo tiene solo caracteres permitidos function allowedCharacters(value, allowedChars) { const escapedChars = allowedChars.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); const regex = new RegExp(`^[${escapedChars}]+$`); return regex.test(value); } // Valida si el campo tiene caracteres prohibidos function disallowedCharacters(value, disallowedChars) { const escapedChars = disallowedChars.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); const regex = new RegExp(`[^${escapedChars}]*$`); return regex.test(value); } // Valida si el campo es un teléfono válido function phone(value) { const regex = /^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s/0-9]*$/; return regex.test(value); } // Valida si el campo es una fecha válida (formato YYYY-MM-DD) function date(value) { const regex = /^\d{4}-\d{2}-\d{2}$/; if (!regex.test(value)) return false; const dateObject = new Date(value); // Compara la fecha con el formato original return dateObject.toISOString().slice(0, 10) === value; } // Valida si el campo tiene solo mayúsculas function isCapitalLetter(value) { return /^[A-Z]+$/.test(value); } // Valida si el campo tiene solo mínusculas function isLowerCase(value) { return /^[a-z]+$/.test(value); } // Valida si el campo permite ambos, mayuscula y minuscula function isBoth(value) { return /^[a-zA-Z]+$/.test(value); } // Valida si el campo tiene saltos de línea function allowsSpaces(value) { return /\s/.test(value); } // Valida si el campo tiene saltos de línea function allowLineBreaks(value) { return /\n/.test(value); } // Validación alphanumeric function alphaNumeric(value) { return /^[a-zA-Z0-9]+$/.test(value); } // Validación Alpha function alpha(value) { return /^[a-zA-Z]+$/.test(value); } // Validación decimal function decimal(value) { return /^\d+(\.\d+)?$/.test(value); } // Método para aplicar validaciones multiples en el DOM function applyValidationOnEvent(control, eventType) { control.addEventListener(eventType, (event) => { const target = event.target; const validationAttr = target.getAttribute('validation-type'); const minLength = parseInt(target.getAttribute('data-min-length') || '0', 10); const maxLength = parseInt(target.getAttribute('data-max-length') || '0', 10); const allowedChars = target.getAttribute('data-allowed-chars') || ''; const disallowedChars = target.getAttribute('data-disallowed-chars') || ''; if (validationAttr) { const validations = validationAttr.split(',').map(v => v.trim()); let valid = true; for (const type of validations) { let currentValid = true; switch (type) { case 'required': currentValid = required(target.value); break; case 'email': currentValid = email(target.value); break; case 'minLength': currentValid = minLengthValid(target.value, minLength); break; case 'maxLength': currentValid = maxLengthValid(target.value, maxLength); break; case 'number': currentValid = isNumber(target.value); break; case 'decimal': currentValid = decimal(target.value); break; case 'phone': currentValid = phone(target.value); break; case 'date': currentValid = date(target.value); break; case 'capital': currentValid = isCapitalLetter(target.value); break; case 'lower': currentValid = isLowerCase(target.value); break; case 'both': currentValid = isBoth(target.value); break; case 'alpha': currentValid = alpha(target.value); break; case 'alphanumeric': currentValid = alphaNumeric(target.value); break; case 'allowed': currentValid = allowedCharacters(target.value, allowedChars); break; case 'disallowed': currentValid = disallowedCharacters(target.value, disallowedChars); break; case 'space': currentValid = !allowsSpaces(target.value); break; case 'newline': currentValid = !allowLineBreaks(target.value); break; default: currentValid = true; } if (!currentValid) { valid = false; break; } } if (!valid) { target.classList.add('invalid'); } else { target.classList.remove('invalid'); } } }); }