Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Validator
- *
- * @module :: Validator
- * @description :: Contains helper for validation.
- */
- var validator = require('validator');
- module.exports = {
- /**
- * @name check
- * @desc Check an entire object using Validator module.
- * @param params {Object|Array} Rules to checks:
- required {Array} Contains all arrays of rules which are REQUIRED and must not be empty or null. One of them array is described below:
- value {*} The value to check.
- key {string} The key in the model. If you don't want to link the field to a model, set it to FALSE. (Can be used for group errors on the same field too)
- rules {Array} Array of Objects:
- function {string} Function to execute. See https://github.com/chriso/node-validator for the entire list.
- message {string} Message to send if one error appends on this rule.
- args {Array} Array of values which contains all parameters. Useful only for methods which need parameters like len, regex, min, max, etc.
- optional {Array of Objects} Contains all arrays of rules which are OPTIONAL and can be empty or null. (Useful when you want update some fields but not all)
- rule {Array} SAME OBJECT THAN THE [required] PREVIOUS FIELD.
- value {*} The value of the field, if null or empty the rule will not be checked. Else, it will be.
- * @param callback {Function} Function to execute after validation, if you don't then the script will return the validation object.
- * @param res {Result object} If res is provides and if at least one error appends then an automatic response will be send using res.json method. If it doesn't you have to manage error message return by your own.
- * @returns {{errors: {messages: Array, status: boolean}, valuesChecked: {}}} Return or data passed in the callback:
- errors {Array}
- messages {Array} Contains an array of all errors found.
- key {string|false} Key of the error, could be one key of the database model. (Useful for dynamic create/update)
- message {string} Message to display.
- status {boolean} If true, at least one error occurred.
- valuesChecked {Object} Contains all [key: value] which were checked.
- * @author Vadorequest
- *
- * @example Callback and res provided
- validator.check([
- validator.rulesEmail(req.params.email),
- validator.rulesPassword(req.params.password)
- ], function(errors, valuesChecked){
- // Do what you want, it's secure because if error appends there will be automatic response. (res provided and auto return if it error occurred)
- }, res);
- * @example Callback and res don't provided
- validator.check([
- validator.rulesEmail(req.params.email),
- validator.rulesPassword(req.params.password)
- ], function(errors, valuesChecked){
- // You have to check for errors by your own.
- if(errors.status){
- // No error occurred.
- }else{
- // Error occurred.
- }
- });
- * @example No callback - You shouldn't use this way
- var validation = validator.check([
- validator.rulesEmail(req.params.email),
- validator.rulesPassword(req.params.password)
- ]);
- * @example Use optional field check with res provided
- validator.check({
- required: [
- validator.rulesUserSessionId(req.session.user.id)
- ], optional: [
- {
- rule: validator.rulesEmail(req.param('email')),
- value: req.param('email')
- }, {
- rule: validator.rulesPassword(req.param('password')),
- value: req.param('password')
- }
- ]
- }, function(errors, valuesChecked){
- // No error occurred. (res provided and auto return if it error occurred)
- // valuesChecked will contains password and email, but only if they wasn't null or empty.
- // You can use [!_.isEmpty(valuesChecked)] for be sure at least one value was passed.
- // You can use [dbHelper.merge(model, valuesChecked)] for merge the valuesChecked with a model dynamically without check for each field if you have to update it.
- }, res);
- */
- check: function(params, callback, res){
- // Contains params checked with values, useful for insert/update queries.
- var valuesChecked = {};
- // Contains only params to check.
- var paramsToCheck = params.required ? params.required : params;
- // Add not null params to paramsToCheck if wanted.
- if(params.optional){
- for (var param in params.optional){
- // If the value is not null or undefined
- if(params.optional[param].value && params.optional[param].value != null && params.optional[param].value != undefined){
- paramsToCheck.push(params.optional[param].rule)
- }
- }
- }
- // Errors object.
- var errors = {
- messages: [],
- status: true// No error.
- };
- if(errors.status){
- // Check each rule.
- for(var i = 0; i < paramsToCheck.length; i++){
- var value = paramsToCheck[i].value;
- var key = (paramsToCheck[i].key !== false ? (paramsToCheck[i].key ? paramsToCheck[i].key : 'undefined'+i) : false);// If false, keep false, else try to get the defined value, if no one then create a dynamic key.
- var rule = paramsToCheck[i].rules;
- for(var j = 0; j < rule.length; j++){
- try{
- var validation = validator.check(value, rule[j].message);
- // Apply parameters if exist.
- if(rule[j].args){
- validation[rule[j].function].apply(validation, rule[j].args);
- }else{
- validation[rule[j].function]();
- }
- // Add the checked value to the array of checked values if not false.
- if(key !== false){
- valuesChecked[key] = value;
- }
- }catch(e){
- errors.messages.push({
- key: key,
- message: (e.message ? e.message : e)// Default is e.message if exists, else the entire message.
- });
- }
- }
- }
- }
- if(errors.messages.length > 0){
- errors.status = false;
- }
- // If res is provided, callback has to be call and if an error appends then we don't do it! Use res for send a response with errors.
- if(res && !errors.status && callback){
- res.json({message: errors[0], data: {errors: errors, typeError: 'Validator'}, status: false});
- }else{
- // Do callback or return results.
- if(callback){
- callback(errors, valuesChecked);
- }else{
- return {
- errors: errors,
- valuesChecked: valuesChecked
- };
- }
- }
- },
- /**
- * ********************************************************************************
- * ********************** Custom your own default rules ***************************
- * ********************************************************************************
- */
- /**
- * Default comportment for user session ID.
- * @param value
- * @param key
- * @returns {{value: *, key: *, rules: Array}}
- */
- rulesUserSessionId: function(value, key){
- return {
- value: value,
- key: false,// We don't want to link this array to a DB model.
- rules: [{
- function: 'notEmpty',
- message: 'Your user session id is empty.'
- }]
- };
- },
- /**
- * Default comportment for Email field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesEmail: function(value){
- var minLength = User.attributes.email.minLength;
- var maxLength = User.attributes.email.maxLength;
- return {
- value: value,
- key: 'email',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: 'Email is required.'
- },{
- function: 'len',
- message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
- args: [minLength, maxLength]
- },{
- function: 'isEmail',
- message: 'Invalid email format.'
- }]
- };
- },
- /**
- * Default comportment for Password field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesPassword: function(value){
- var minLength = User.attributes.password.minLength;
- var maxLength = User.attributes.password.maxLength;
- return {
- value: value,
- key: 'password',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: 'Password is required.'
- },{
- function: 'len',
- message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
- args: [minLength, maxLength]
- }]
- };
- },
- /**
- * Default comportment for Database auto-generated ID field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesId: function(value, id, messageEmpty){
- var length = 24;
- return {
- value: value,
- key: id ? id : 'id',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: messageEmpty ? messageEmpty : 'An ID is empty.'
- },{
- function: 'len',
- message: 'The length of an ID must be '+length+' characters.',
- args: [length, length]
- }]
- };
- },
- /**
- * Default comportment for Label field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesLabel: function(value){
- var minLength = Device.attributes.label.minLength;
- var maxLength = Device.attributes.label.maxLength;
- return {
- value: value,
- key: 'label',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: 'Label is required.'
- },{
- function: 'len',
- message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
- args: [minLength, maxLength]
- }]
- };
- },
- /**
- * Default comportment for HardwareId field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesHardwareId: function(value){
- var minLength = Device.attributes.hardwareId.minLength;
- var maxLength = Device.attributes.hardwareId.maxLength;
- return {
- value: value,
- key: 'hardwareId',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: 'Hardware id is required.'
- },{
- function: 'len',
- message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
- args: [minLength, maxLength]
- }]
- };
- },
- /**
- * Default comportment for RefreshFrequency field.
- * @param value
- * @returns {{value: *, key: string, rules: Array}}
- */
- rulesRefreshFrequency: function(value){
- var min = Device.attributes.refreshFrequency.min;
- var max = Device.attributes.refreshFrequency.max;
- return {
- value: value,
- key: 'details',// Must be the key in the Model.
- rules: [{
- function: 'notEmpty',
- message: 'Frequency is required.'
- },{
- function: 'min',
- message: 'The min frequency is '+min+'.',
- args: [min]
- },{
- function: 'max',
- message: 'The max frequency is '+max+'.',
- args: [max]
- }]
- };
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement