UNPKG

js-model-validation

Version:

js-model-validation is js model validation lib to validate the model property. It's allow range of property validations like 'string', 'number', 'json' etc. It's not only validate the model but also return the data from 'req.body' (if node app).

145 lines (136 loc) 5.66 kB
module.exports = async (req, columns, config) => { /**/ /* columns [{ name: 'columns name', type: 'column type', default set to 'string' -> [string, email, number, date, json, array] validation: { required: true, -> true or false (false will ignore all the validation for the column) message: '[column] is required.', min: 0, string or number column allowed input, default 0 when required set to true max: 50, string or number column allowed input, default 'max' rangmessage: 'min 3 and max 20', only display when min, max or min and max values are provided }, nesteditems: false, default set to false, when set to true 'validationitems' need to set and for this 'name', 'type', validation and other attribute ignored. validationitems: [ name: 'column name', type: 'column type', ..... ] }] */ /* config -> config is optional showAllMessage: boolean -> default set to false { true: Display all the error messages. false: Display first found error messages. } */ /* req or validation data */ let dataList = {}; let errorList = []; if (Array.isArray(columns)) { try { const data = (!req.body) ? req : req.body; sails.log.info(req.body); for (const column of columns) { if (column.nesteditems) { let err = this.validateService(column, column.config || { showAllMessage: false }, column.validationitems); errorList.push(err); } else { if (column.validation || columns.required) { await addError(column, data[column.name]); } } } } catch (error) { return { iserror: true, errors: error } } if (Object.keys(errorList).length > 0) { return { iserror: true, errors: errorList } } return { iserror: false, data: dataList } } async function addError(column, value) { let error = await errorMessage(column, value); if (error) { errorList.push({ name: column.name, message: error }); } else if (Object.keys(errorList).length <= 0) { dataList[column.name] = value; } } async function errorMessage(column, value) { let columnType = column.type || 'string'; let isRequired = column.validation.required || column.required; if (isRequired && (!value || value.length <= 0)) { return `${column.name} is required.`; } else if (columnType == 'number' && isNaN(value)) { return `${column.name} has invalid value. Number is required.`; } else if (columnType == 'json') { try { JSON.parse(value); } catch (e) { return `${column.name} has invalid json value.`; } } else if (columnType == 'array' && !Array.isArray(value)) { return `${column.name} has invalid array value.`; } else if (columnType == 'email' && !validateEmail(value)) { return `${column.name} has invalid email value.`; } else if (columnType == 'date') { try { if (new Date(value) == 'Invalid Date') { return `${column.name} has invalid date value.`; } } catch (e) { return `${column.name} has invalid date value.`; } } if (column.validation) { let stringMsg = (!column.validation.message) ? `${column.name} is required.` : column.validation.message; if ((column.validation.required || isRequired) && !value) { return stringMsg; } let minValue = column.validation.min; let maxValue = column.validation.max; let valueLength = (!value) ? 0 : value.length; let rangeMsg = (!column.validation.rangemessage) ? `${column.name} min ${minValue} & max ${maxValue} is required` : column.validation.rangemessage; if (minValue > valueLength && !maxValue) { return (!column.validation.rangemessage) ? `${column.name} min value ${minValue}` : column.validation.rangemessage; } else if (maxValue < valueLength && !minValue) { return (!column.validation.rangemessage) ? `${column.name} max value ${maxValue}` : column.validation.rangemessage; } else if (valueLength > maxValue || valueLength < minValue) { return rangeMsg; } } } async function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } async function throwError(errorof) { switch (errorof) { case 'columns': throw new Error('columns is not an array. please ref to the validation config.'); default: break; } } }