76 lines
1.6 KiB
JavaScript
76 lines
1.6 KiB
JavaScript
const validator = require('validator');
|
|
const moment = require('moment');
|
|
|
|
const noValido = (campo) => {
|
|
throw new Error(`El ${campo} no es valido.`);
|
|
};
|
|
|
|
const noHay = (variable, campo) => {
|
|
if (!variable) throw new Error(`Falta ${campo}.`);
|
|
};
|
|
|
|
const yaExiste = (campo) => {
|
|
throw new Error(`El ${campo} ya se encuentra en uso.`);
|
|
};
|
|
|
|
const validarId = (id) => {
|
|
let campo = 'id';
|
|
|
|
noHay(id, campo);
|
|
if (typeof id === 'number') id = id.toString();
|
|
if (typeof id !== 'string' || !validator.isNumeric(id, { no_symbols: true }))
|
|
noValido(campo);
|
|
return Number(id);
|
|
};
|
|
|
|
const validarCorreo = (correo) => {
|
|
let campo = 'correo';
|
|
|
|
noHay(correo, campo);
|
|
if (typeof correo !== 'string' || !validator.isEmail(correo)) noValido(campo);
|
|
return correo;
|
|
};
|
|
|
|
const validarTexto = (texto, campo) => {
|
|
noHay(texto, campo);
|
|
if (typeof texto !== 'string') noValido(campo);
|
|
for (let i = 0; i < texto.length; i++) {
|
|
if (texto[i] === ' ') continue;
|
|
if (!validator.isAlpha(texto[i], 'es-ES')) noValido(campo);
|
|
}
|
|
return texto;
|
|
};
|
|
|
|
const validarNumeroCuenta = (numeroCuenta) => {
|
|
let campo = 'numero de cuenta';
|
|
|
|
noHay(numeroCuenta, campo);
|
|
if (
|
|
typeof numeroCuenta !== 'string' ||
|
|
!validator.isNumeric(numeroCuenta, { no_symbols: true }) ||
|
|
numeroCuenta.length > 9
|
|
)
|
|
noValido(campo);
|
|
return numeroCuenta;
|
|
};
|
|
|
|
const validarFecha = (fecha) => {
|
|
let campo = 'fecha';
|
|
let fechaMoment = moment(fecha);
|
|
|
|
noHay(fecha, campo);
|
|
if (fechaMoment.isValid()) noValido(campo);
|
|
return fechaMoment;
|
|
};
|
|
|
|
module.exports = {
|
|
noValido,
|
|
yaExiste,
|
|
noHay,
|
|
validarCorreo,
|
|
validarId,
|
|
validarTexto,
|
|
validarNumeroCuenta,
|
|
validarFecha,
|
|
};
|