Advertisement
Vadorequest

validator.js

Jan 15th, 2014
92
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.  * @requires Validator https://github.com/chriso/node-validator
  7.  */
  8. var validator = require('validator');
  9.  
  10. module.exports = {
  11.     /**
  12.      * @name        check
  13.      * @desc        Check an entire object using Validator module.
  14.      * @param       params {Object|Array} Rules to checks. If required doesn't exists then params is used like the required array. (
  15.                         required {Array} Contains all arrays of rules which are REQUIRED and must not be empty or null.
  16.                         optional {Array} Contains all arrays of rules which are OPTIONAL and can be empty or null. One of them array is described below: (Use the same array than the [required] field)
  17.                             value {*} The value to check.
  18.                             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)
  19.                             rules {Array} Array of Objects:
  20.                                 function {string} Function to execute. See https://github.com/chriso/node-validator for the entire list.
  21.                                 message {string} Message to send if one error appends on this rule.
  22.                                 args {Array} Array of values which contains all parameters. Useful only for methods which need parameters like len, regex, min, max, etc.
  23.      * @param       callback {Function} Function to execute after validation, if you don't then the script will return the validation object.
  24.      * @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.
  25.      * @returns     {{errors: {messages: Array, status: boolean}, typeError: 'V', keysModelChecked: {}, keysChecked: {}}} Return or data passed in the callback:
  26.                         errors {Array}
  27.                             messages {Array} Contains an array of all errors found.
  28.                                 key {string|false} Key of the error, could be one key of the database model. (Useful for dynamic create/update)
  29.                                 message {string} Message to display.
  30.                             status {boolean} If true, at least one error occurred.
  31.                         keysModelChecked {Object} Contains [key: value] which belong to a model and were checked.
  32.                         keysChecked {Object} Contains all [key: value] other checked keys.
  33.  
  34.      * @author      Vadorequest
  35.      *
  36.      * @example     Callback and res provided
  37.                         __validator.check([
  38.                             __validator.rulesUserEmail(req.params.email),
  39.                             __validator.rulesUserPasswordProtected(req.params.password)
  40.                         ], function(errors, keysModelChecked, keysChecked){
  41.                             // 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)
  42.                         }, res);
  43.  
  44.      * @example     Callback and res don't provided
  45.                         __validator.check([
  46.                             __validator.rulesUserEmail(req.params.email),
  47.                             __validator.rulesUserPasswordProtected(req.params.password)
  48.                         ], function(errors, keysModelChecked, keysChecked){
  49.                             // You have to check for errors by your own.
  50.                             if(errors.status){
  51.                                 // No error occurred.
  52.                             }else{
  53.                                 // Error occurred.
  54.                             }
  55.                         });
  56.  
  57.      * @example     No callback - You shouldn't use this way
  58.                         var validation = __validator.check([
  59.                             __validator.rulesUserEmail(req.params.email),
  60.                             __validator.rulesUserPasswordProtected(req.params.password)
  61.                         ]);
  62.  
  63.      * @example     Use optional field check with res provided
  64.                         __validator.check({
  65.                             required: [
  66.                                 __validator.rulesUserSessionId(req.session.user.id)
  67.                             ],
  68.                             optional: [
  69.                                 __validator.rulesUserEmail(req.param('email')),
  70.                                 __validator.rulesUserPasswordProtected(req.param('password'))
  71.                             ]
  72.                         }, function(errors, keysModelChecked, keysChecked){
  73.                             // No error occurred. (res provided and auto return if it error occurred)
  74.                             // keysModelChecked will contains password and email, but only if they wasn't null or empty.
  75.                             // You can use [!_.isEmpty(keysModelChecked)] for be sure at least one value was passed.
  76.                             // You can use [dbHelper.merge(model, keysModelChecked)] for merge the keysModelChecked with a model dynamically without check for each field if you have to update it.
  77.                         }, res);
  78.      */
  79.     check: function(params, callback, res){
  80.         // Contains params checked with values, useful for insert/update queries.
  81.         var keysModelChecked = {};
  82.  
  83.         // Contains all other non model keys checked.
  84.         var keysChecked = {};
  85.  
  86.         // Contains only params to check.
  87.         var paramsToCheck = params.required ? params.required : params;
  88.  
  89.         // Add not null params to paramsToCheck if wanted.
  90.         if(params.optional){
  91.             for (var i = 0; i < params.optional.length; i++){
  92.                 // If the value is not null or undefined
  93.                 if(params.optional[i].value && params.optional[i].value != null && params.optional[i].value != undefined){
  94.                     paramsToCheck.push(params.optional[i])
  95.                 }
  96.             }
  97.         }
  98.  
  99.         // Errors handler.
  100.         var validatorMessage = new __validatorMessage();
  101.  
  102.         // Check each rule.
  103.         for(var i = 0; i < paramsToCheck.length; i++){
  104.             var value = paramsToCheck[i].value;
  105.             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.
  106.             var rule = paramsToCheck[i].rules;
  107.             var model = paramsToCheck[i].model;
  108.  
  109.             // Check every rules.
  110.             for(var j = 0; j < rule.length; j++){
  111.                 try{
  112.                     var validation = validator.check(value, rule[j].message);
  113.  
  114.                     // If we use our custom object, use it instead of the default Validator message. (Their lib will replace our object by the default message)
  115.                     if(validation.msg == null && typeof rule[j].message !== 'string'){
  116.                         validation.msg = rule[j].message;
  117.                     }
  118.  
  119.                     // Apply parameters if exist.
  120.                     if(rule[j].args){
  121.                         validation[rule[j].function].apply(validation, rule[j].args);
  122.                     }else{
  123.                         validation[rule[j].function]();
  124.                     }
  125.                 }catch(e){
  126.                     // When an exception is raise that means there is a validation error. (Or real exception!)
  127.                     validatorMessage.addError( e.message ? e.message : e, key, rule[j].args);
  128.                 }
  129.             }
  130.  
  131.             // Add the key=>value to the keys that belong to a model.
  132.             if(key !== false && model === true){
  133.                 keysModelChecked[key] = value;
  134.             }else if(key !== false){
  135.                 // Add the key=>value to the other keys, that don't belong to a model.
  136.                 keysChecked[key] = value;
  137.             }
  138.         }
  139.  
  140.         // 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.
  141.         if(res && !validatorMessage.getStatus() && callback){
  142.             return res.json(__format.response(validatorMessage));
  143.         }else{
  144.             // Bind the data into the validatorMessage anyway.
  145.             validatorMessage.addData('keysModelChecked', keysModelChecked);
  146.             validatorMessage.addData('keysChecked', keysChecked);
  147.  
  148.             // Do callback or return results.
  149.             if(callback){
  150.                 // Send also the keys avoid a request on the validatorMessage each time to get them.
  151.                 return callback(validatorMessage, keysModelChecked, keysChecked);
  152.             }else{
  153.                 return validatorMessage;
  154.             }
  155.         }
  156.     },
  157.  
  158.     /**
  159.      * ********************************************************************************
  160.      * ********************************* Default rules ********************************
  161.      * ********************************************************************************
  162.      */
  163.  
  164.     /**
  165.      * Default comportment for Folder name field.
  166.      */
  167.     rulesFolderName: function(value){
  168.         var minLength = 4;
  169.         var maxLength = 16;
  170.  
  171.         return {
  172.             value: value,
  173.             key: 'folderName',
  174.             model: false,
  175.             rules: [{
  176.                 function: 'notEmpty',
  177.                 message: 'Folder Name is required.'
  178.             },{
  179.                 function: 'len',
  180.                 args: [minLength, maxLength],
  181.                 message: {
  182.                     "m": "__10_11",
  183.                     "a": [minLength, maxLength]
  184.                 }
  185.             },{
  186.                 function: 'regex',
  187.                 args: ['^[a-zA-Z0-9 _-]{'+minLength+','+maxLength+'}$', 'i'],
  188.                 message: 'The folder name must be contains only letters, numbers and "-". Nothing else.'
  189.             }]
  190.         };
  191.     },
  192.  
  193.     /**
  194.      * Default comportment for Resource name field.
  195.      * @param       value {string}
  196.      */
  197.     rulesResourceName: function(value){
  198.         var minLength = 4;
  199.         var maxLength = 20;
  200.  
  201.         return {
  202.             value: value,
  203.             key: 'resourceName',
  204.             model: false,
  205.             rules: [{
  206.                 function: 'notEmpty',
  207.                 message: 'Folder Name is required.'
  208.             },{
  209.                 function: 'len',
  210.                 args: [minLength, maxLength],
  211.                 message: {
  212.                     "m": "__10_11",
  213.                     "a": [minLength, maxLength]
  214.                 }
  215.             },{
  216.                 function: 'regex',
  217.                 args: ['^[a-zA-Z0-9 _-]{'+minLength+','+maxLength+'}$', 'i'],
  218.                 message: 'The folder name must be contains only letters, numbers and "-". Nothing else.'
  219.             }]
  220.         };
  221.     },
  222.  
  223.     /**
  224.      * Default comportment for World name field.
  225.      */
  226.     rulesWorldName: function(value){
  227.         var minLength = 4;
  228.         var maxLength = 20;
  229.  
  230.         return {
  231.             value: value,
  232.             key: 'worldName',
  233.             model: false,
  234.             rules: [{
  235.                 function: 'notEmpty',
  236.                 message: 'Folder Name is required.'
  237.             },{
  238.                 function: 'len',
  239.                 args: [minLength, maxLength],
  240.                 message: {
  241.                     "m": "__10_11",
  242.                     "a": [minLength, maxLength]
  243.                 }
  244.             },{
  245.                 function: 'regex',
  246.                 args: ['^[a-zA-Z0-9 _-]{'+minLength+','+maxLength+'}$', 'i'],
  247.                 message: 'The World name must be contains only letters, numbers and "-". Nothing else.'
  248.             }]
  249.         };
  250.     },
  251.  
  252.     /**
  253.      * Default comportment for user session ID.
  254.      * @param       value {*}
  255.      * @returns     {{value: *, key: *, rules: Array}}
  256.      */
  257.     rulesUserSessionId: function(value){
  258.         return {
  259.             value: value,
  260.             key: 'userSessionId',
  261.             model: false,
  262.             rules: [{
  263.                 function: 'notEmpty',
  264.                 message: 'Your user session id is empty.'
  265.             }]
  266.         };
  267.     },
  268.  
  269.     /**
  270.      * Default comportment for Database auto-generated ID field.
  271.      * @param       value {*}
  272.      * @param       key {string} Key to use for auto bind the field to a model field.
  273.      * @param       messageEmpty {string} Message to display if the value is empty.
  274.      * @returns     {{value: *, key: string, rules: Array}}
  275.      */
  276.     rulesId: function(value, key, messageEmpty){
  277.         var minLength = 24;
  278.         var maxLength = 30;
  279.  
  280.         return {
  281.             value: value,
  282.             key: key ? key : false,// Don't link to the model if the key is not defined.
  283.             model: true,
  284.             rules: [{
  285.                 function: 'notEmpty',
  286.                 message: messageEmpty ? messageEmpty : 'An ID is empty.'
  287.             },{
  288.                 function: 'len',
  289.                 args: [minLength, maxLength],
  290.                 message: 'The length of an ID must be more than '+minLength+' characters.'
  291.             }]
  292.         };
  293.     },
  294.  
  295.     /**
  296.      * Default comportment for Database auto-query limit field.
  297.      * @param       value {int}
  298.      * @returns     {{value: *, key: *, rules: Array}}
  299.      */
  300.     rulesLimit: function(value){
  301.         var min = 1;
  302.  
  303.         return {
  304.             value: value,
  305.             key: 'limit',
  306.             model: true,
  307.             rules: [{
  308.                 function: 'isInt',
  309.                 message: 'The limit must be an integer.'
  310.             }, {
  311.                 function: 'min',
  312.                 args: [min],
  313.                 message: 'The min limit value is '+min+'.'
  314.             }]
  315.         };
  316.     },
  317.  
  318.     /**
  319.      * Useful in some cases for add a field without check.
  320.      * @param       value {*}
  321.      * @param       key {string} Key to use for auto bind the field to a model field.
  322.      * @param       model {boolean} Key to use for auto bind the field to a model field.
  323.      * @returns     {{value: *, key: *, rules: Array}}
  324.      */
  325.     rulesEmpty: function(value, key, model){
  326.         return {
  327.             value: value,
  328.             key: key ? key : false,// Don't link to the model if the key is not defined.
  329.             model: model ? model : false,
  330.             rules: []
  331.         };
  332.     },
  333.  
  334.     /**
  335.      * ********************************************************************************
  336.      * ********************** Custom your own default rules ***************************
  337.      * ********************************************************************************
  338.      */
  339.  
  340.     /**
  341.      * Default comportment for Login field.
  342.      * @param       value {string}
  343.      * @returns     {{value: *, key: string, rules: Array}}
  344.      */
  345.     rulesUserLogin: function(value){
  346.         var minLength = __Dao.getSchema('user').login.check.minLength;
  347.         var maxLength = __Dao.getSchema('user').login.check.maxLength;
  348.  
  349.         return {
  350.             value: value,
  351.             key: 'login',
  352.             model: true,
  353.             rules: [{
  354.                 function: 'notEmpty',
  355.                 message: '__2'
  356.             },{
  357.                 function: 'regex',
  358.                 args: ['^[a-zA-Z0-9_-]{'+minLength+','+maxLength+'}$', 'i'],
  359.                 message: '__1'
  360.             },{
  361.                 function: 'len',
  362.                 args: [minLength, maxLength],
  363.                 message: {
  364.                     "m": "__12",
  365.                     "a": [minLength, maxLength]
  366.                 }
  367.             }]
  368.         };
  369.     },
  370.  
  371.     /**
  372.      * Default comportment for email field.
  373.      * @param       value {string}
  374.      * @returns     {{value: *, key: string, rules: Array}}
  375.      * TODO Use a local instance of user instead of several loads.
  376.      */
  377.     rulesUserEmail: function(value){
  378.         var minLength = __Dao.getSchema('user').email.check.minLength;
  379.         var maxLength = __Dao.getSchema('user').email.check.maxLength;
  380.  
  381.         return {
  382.             value: value,
  383.             key: 'email',// Must be the key in the Model.
  384.             model: true,
  385.             rules: [{
  386.                 function: 'notEmpty',
  387.                 message: '__10_14'
  388.             },{
  389.                 function: 'len',
  390.                 args: [minLength, maxLength],
  391.                 message: {
  392.                     "m": "__10_11",
  393.                     "a": [minLength, maxLength]
  394.                 }
  395.             },{
  396.                 function: 'isEmail',
  397.                 message: '__10_13'
  398.             }]
  399.         };
  400.     },
  401.  
  402.     /**
  403.      * Default comportment for password field.
  404.      * @param       value {string}
  405.      * @returns     {{value: *, key: string, rules: Array}}
  406.      */
  407.     rulesUserPasswordProtected: function(value){
  408.         var minLength = __Dao.getSchema('user').passwordProtected.check.minLength;
  409.         //var maxLength = __Dao.getSchema('user').password.maxLength;
  410.  
  411.         return {
  412.             value: value,
  413.             key: 'password',// Must be the key in the Model.
  414.             model: true,
  415.             rules: [{
  416.                 function: 'notEmpty',
  417.                 message: '__8'
  418.             },{
  419.                 function: 'len',
  420.                 args: [63, 65],
  421.                 message: "__13"
  422.             }]
  423.         };
  424.     }
  425. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement