96 lines
2.0 KiB
JavaScript
96 lines
2.0 KiB
JavaScript
const validator = require('validator');
|
|
const moment = require('moment');
|
|
|
|
const noValido = (campo) => {
|
|
throw new Error(`${campo} no es valido.`);
|
|
};
|
|
|
|
const noHay = (variable, campo) => {
|
|
if (!variable) throw new Error(`Falta ${campo}.`);
|
|
};
|
|
|
|
const yaExiste = (campo) => {
|
|
throw new Error(`${campo} ya se encuentra en uso.`);
|
|
};
|
|
|
|
const validar = (texto, campo) => {
|
|
noHay(texto, campo);
|
|
if (typeof texto !== 'string') noValido(campo);
|
|
return texto;
|
|
};
|
|
|
|
const validarId = (id) => {
|
|
let campo = 'El 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 = 'El 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 = 'El 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 = 'La fecha';
|
|
let fechaMoment = moment(fecha);
|
|
|
|
noHay(fecha, campo);
|
|
if (!fechaMoment.isValid()) noValido(campo);
|
|
return fechaMoment;
|
|
};
|
|
|
|
const validarNumero = (numero) => {
|
|
let campo = 'El numero';
|
|
|
|
noHay(numero, campo);
|
|
if (
|
|
typeof numero !== 'string' ||
|
|
!validator.isNumeric(numero, { no_symbols: true })
|
|
)
|
|
noValido(campo);
|
|
return numero;
|
|
};
|
|
|
|
module.exports = {
|
|
validar,
|
|
noValido,
|
|
yaExiste,
|
|
noHay,
|
|
validarCorreo,
|
|
validarId,
|
|
validarTexto,
|
|
validarNumeroCuenta,
|
|
validarFecha,
|
|
validarNumero,
|
|
};
|