Advertisement
Vadorequest

services/validator.js Final version 1.0

Sep 29th, 2013
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Validator
  3.  *
  4.  * @module      :: Validator
  5.  * @description :: Contains helper for validation.
  6.  */
  7. var validator = require('validator');
  8.  
  9. module.exports = {
  10.     /**
  11.      * Check an entire object using Validator module. DON'T WORKS.
  12.      * @param params {Object} Rules to checks:
  13.             value {*} The value to check.
  14.             label {string} The label to use for all errors on this value. (Can be used for group errors on the same field)
  15.             rules {Array} Array of Objects:
  16.                 function {string} Function to execute. See https://github.com/chriso/node-validator for the entire list.
  17.                 message {string} Message to send if one error appends on this rule.
  18.                 args {Array} Array of values which contains all parameters. Useful only for methods which need parameters like len, regex, min, max, etc.
  19.      * @param callback {Function} Function to execute after validation, if you don't then the script will return the validation object.
  20.      * @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.
  21.      * @returns {{messages: Array, status: boolean}}
  22.      *
  23.      * @example Callback and res provided
  24.          validator.check([
  25.              validator.rulesEmail(req.params.email),
  26.              validator.rulesPassword(req.params.password)
  27.          ], function(validation){
  28.             // Do what you want, it's secure because if error appends there will be automatic response. (res is provided)
  29.          }, res);
  30.  
  31.      * @example Callback and res don't provided
  32.          validator.check([
  33.              validator.rulesEmail(req.params.email),
  34.              validator.rulesPassword(req.params.password)
  35.          ], function(result){
  36.             // You have to check for errors by your own.
  37.             if(validation.status){
  38.                 // No error appends.
  39.             }else{
  40.                 // Error appends.
  41.             }
  42.          });
  43.  
  44.      * @example No callback
  45.         var validation = validator.check([
  46.             validator.rulesEmail(req.params.email),
  47.             validator.rulesPassword(req.params.password)
  48.         ]);
  49.      */
  50.     check: function(params, callback, res){
  51.         // Errors object.
  52.         var errors = {
  53.             messages: [],
  54.             status: true// No error.
  55.         };
  56.  
  57.         // Check params object content. (Help for developers)
  58.         if((!params || params.length === 0)){
  59.             errors.messages.push({
  60.                 type: 'Debug',
  61.                 file: 'validator.js',
  62.                 method: 'check',
  63.                 message: 'The first arg must be an array which must contains at least one object.'
  64.             });
  65.             errors.status = false;
  66.         }
  67.  
  68.         if(errors.status){
  69.             // Check each rule.
  70.             for(var i = 0; i < params.length; i++){
  71.                 try{
  72.                     var value = params[i].value;
  73.                     var label = (params[i].label ? params[i].label : i);
  74.                     var rule = params[i].rules;
  75.                     for(var j = 0; j < rule.length; j++){
  76.                         try{
  77.                             var validation = validator.check(value, rule[j].message);
  78.  
  79.                             // Apply parameters if exist.
  80.                             if(rule[j].args){
  81.                                 validation[rule[j].function].apply(validation, rule[j].args);
  82.                             }else{
  83.                                 validation[rule[j].function]();
  84.                             }
  85.                         }catch(e){
  86.                             errors.messages.push({
  87.                                 type: 'Error',
  88.                                 label: label,
  89.                                 message: (e.message ? e.message : e)// Default is e.message, if exists, else the entire message.
  90.                             });
  91.                         }
  92.                     }
  93.                 }catch(e){
  94.                     errors.messages.push({
  95.                         type: 'Debug',
  96.                         message: (e.message ? e.message : e)// Default is e.message, if exists, else the entire message.
  97.                     });
  98.                 }
  99.             }
  100.         }
  101.  
  102.         if(errors.messages.length > 0){
  103.             errors.status = false;
  104.         }
  105.  
  106.         // 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.
  107.         if(res && !errors.status && callback){
  108.             res.json({message: 'Errors append.', data: {errors: errors}, status: false});
  109.         }else{
  110.             // Do callback or return results.
  111.             if(callback){
  112.                 callback(errors);
  113.             }else{
  114.                 return errors;
  115.             }
  116.         }
  117.     },
  118.  
  119.     /**
  120.      * ********************************************************************************
  121.      * ********************** Custom your own default rules ***************************
  122.      * ********************************************************************************
  123.      */
  124.  
  125.     /**
  126.      * Default comportment pour Email field.
  127.      * @param value
  128.      * @returns {{value: *, label: string, rules: Array}}
  129.      */
  130.     rulesEmail: function(value){
  131.         return {
  132.             value: value,
  133.             label: 'Email',
  134.             rules: [{
  135.                 function: 'notEmpty',
  136.                 message: 'Email is mandatory.'
  137.             },{
  138.                 function: 'len',
  139.                 message: 'The min length is 6. Max length is 64.',
  140.                 args: [6, 64]
  141.             },{
  142.                 function: 'isEmail',
  143.                 message: 'Invalid email format.'
  144.             }]
  145.         };
  146.     },
  147.  
  148.     /**
  149.      * Default comportment pour Password field.
  150.      * @param value
  151.      * @returns {{value: *, label: string, rules: Array}}
  152.      */
  153.     rulesPassword: function(value){
  154.         return {
  155.             value: value,
  156.             label: 'Password',
  157.             rules: [{
  158.                 function: 'notEmpty',
  159.                 message: 'Password is mandatory.'
  160.             },{
  161.                 function: 'len',
  162.                 message: 'The min length is 4. Max length is 20.',
  163.                 args: [3, 20]
  164.             }]
  165.         };
  166.     }
  167. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement