Advertisement
Vadorequest

validator.js

Oct 6th, 2013
116
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.      * @name        check
  12.      * @desc        Check an entire object using Validator module.
  13.      * @param       params {Object|Array} Rules to checks:
  14.                         required {Array} Contains all arrays of rules which are REQUIRED and must not be empty or null. One of them array is described below:
  15.                             value {*} The value to check.
  16.                             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)
  17.                             rules {Array} Array of Objects:
  18.                                 function {string} Function to execute. See https://github.com/chriso/node-validator for the entire list.
  19.                                 message {string} Message to send if one error appends on this rule.
  20.                                 args {Array} Array of values which contains all parameters. Useful only for methods which need parameters like len, regex, min, max, etc.
  21.                         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)
  22.                             rule {Array} SAME OBJECT THAN THE [required] PREVIOUS FIELD.
  23.                             value {*} The value of the field, if null or empty the rule will not be checked. Else, it will be.
  24.      * @param       callback {Function} Function to execute after validation, if you don't then the script will return the validation object.
  25.      * @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.
  26.      * @returns     {{errors: {messages: Array, status: boolean}, valuesChecked: {}}} Return or data passed in the callback:
  27.                         errors {Array}
  28.                             messages {Array} Contains an array of all errors found.
  29.                                 key {string|false} Key of the error, could be one key of the database model. (Useful for dynamic create/update)
  30.                                 message {string} Message to display.
  31.                             status {boolean} If true, at least one error occurred.
  32.                         valuesChecked {Object} Contains all [key: value] which were checked.
  33.  
  34.      * @author      Vadorequest
  35.      *
  36.      * @example     Callback and res provided
  37.                         validator.check([
  38.                             validator.rulesEmail(req.params.email),
  39.                             validator.rulesPassword(req.params.password)
  40.                         ], function(errors, valuesChecked){
  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.rulesEmail(req.params.email),
  47.                             validator.rulesPassword(req.params.password)
  48.                         ], function(errors, valuesChecked){
  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.rulesEmail(req.params.email),
  60.                             validator.rulesPassword(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.                             ], optional: [
  68.                                 {
  69.                                     rule: validator.rulesEmail(req.param('email')),
  70.                                     value: req.param('email')
  71.                                 }, {
  72.                                     rule: validator.rulesPassword(req.param('password')),
  73.                                     value: req.param('password')
  74.                                 }
  75.                             ]
  76.                         }, function(errors, valuesChecked){
  77.                             // No error occurred. (res provided and auto return if it error occurred)
  78.                             // valuesChecked will contains password and email, but only if they wasn't null or empty.
  79.                             // You can use [!_.isEmpty(valuesChecked)] for be sure at least one value was passed.
  80.                             // 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.
  81.                         }, res);
  82.      */
  83.     check: function(params, callback, res){
  84.         // Contains params checked with values, useful for insert/update queries.
  85.         var valuesChecked = {};
  86.  
  87.         // Contains only params to check.
  88.         var paramsToCheck = params.required ? params.required : params;
  89.  
  90.         // Add not null params to paramsToCheck if wanted.
  91.         if(params.optional){
  92.             for (var param in params.optional){
  93.                 // If the value is not null or undefined
  94.                 if(params.optional[param].value && params.optional[param].value != null && params.optional[param].value != undefined){
  95.                     paramsToCheck.push(params.optional[param].rule)
  96.                 }
  97.             }
  98.         }
  99.  
  100.         // Errors object.
  101.         var errors = {
  102.             messages: [],
  103.             status: true// No error.
  104.         };
  105.  
  106.  
  107.  
  108.         if(errors.status){
  109.             // Check each rule.
  110.             for(var i = 0; i < paramsToCheck.length; i++){
  111.                 var value = paramsToCheck[i].value;
  112.                 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.
  113.                 var rule = paramsToCheck[i].rules;
  114.                 for(var j = 0; j < rule.length; j++){
  115.                     try{
  116.                         var validation = validator.check(value, rule[j].message);
  117.  
  118.                         // Apply parameters if exist.
  119.                         if(rule[j].args){
  120.                             validation[rule[j].function].apply(validation, rule[j].args);
  121.                         }else{
  122.                             validation[rule[j].function]();
  123.                         }
  124.  
  125.                         // Add the checked value to the array of checked values if not false.
  126.                         if(key !== false){
  127.                             valuesChecked[key] = value;
  128.                         }
  129.                     }catch(e){
  130.                         errors.messages.push({
  131.                             key: key,
  132.                             message: (e.message ? e.message : e)// Default is e.message if exists, else the entire message.
  133.                         });
  134.                     }
  135.                 }
  136.             }
  137.         }
  138.  
  139.         if(errors.messages.length > 0){
  140.             errors.status = false;
  141.         }
  142.  
  143.         // 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.
  144.         if(res && !errors.status && callback){
  145.             res.json({message: errors[0], data: {errors: errors, typeError: 'Validator'}, status: false});
  146.         }else{
  147.             // Do callback or return results.
  148.             if(callback){
  149.                 callback(errors, valuesChecked);
  150.             }else{
  151.                 return {
  152.                     errors: errors,
  153.                     valuesChecked: valuesChecked
  154.                 };
  155.             }
  156.         }
  157.     },
  158.  
  159.     /**
  160.      * ********************************************************************************
  161.      * ********************** Custom your own default rules ***************************
  162.      * ********************************************************************************
  163.      */
  164.  
  165.     /**
  166.      * Default comportment for user session ID.
  167.      * @param value
  168.      * @param key
  169.      * @returns {{value: *, key: *, rules: Array}}
  170.      */
  171.     rulesUserSessionId: function(value, key){
  172.         return {
  173.             value: value,
  174.             key: false,// We don't want to link this array to a DB model.
  175.             rules: [{
  176.                 function: 'notEmpty',
  177.                 message: 'Your user session id is empty.'
  178.             }]
  179.         };
  180.     },
  181.  
  182.     /**
  183.      * Default comportment for Email field.
  184.      * @param value
  185.      * @returns {{value: *, key: string, rules: Array}}
  186.      */
  187.     rulesEmail: function(value){
  188.         var minLength = User.attributes.email.minLength;
  189.         var maxLength = User.attributes.email.maxLength;
  190.  
  191.         return {
  192.             value: value,
  193.             key: 'email',// Must be the key in the Model.
  194.             rules: [{
  195.                 function: 'notEmpty',
  196.                 message: 'Email is required.'
  197.             },{
  198.                 function: 'len',
  199.                 message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
  200.                 args: [minLength, maxLength]
  201.             },{
  202.                 function: 'isEmail',
  203.                 message: 'Invalid email format.'
  204.             }]
  205.         };
  206.     },
  207.  
  208.     /**
  209.      * Default comportment for Password field.
  210.      * @param value
  211.      * @returns {{value: *, key: string, rules: Array}}
  212.      */
  213.     rulesPassword: function(value){
  214.         var minLength = User.attributes.password.minLength;
  215.         var maxLength = User.attributes.password.maxLength;
  216.  
  217.         return {
  218.             value: value,
  219.             key: 'password',// Must be the key in the Model.
  220.             rules: [{
  221.                 function: 'notEmpty',
  222.                 message: 'Password is required.'
  223.             },{
  224.                 function: 'len',
  225.                 message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
  226.                 args: [minLength, maxLength]
  227.             }]
  228.         };
  229.     },
  230.  
  231.     /**
  232.      * Default comportment for Database auto-generated ID field.
  233.      * @param value
  234.      * @returns {{value: *, key: string, rules: Array}}
  235.      */
  236.     rulesId: function(value, id, messageEmpty){
  237.         var length = 24;
  238.  
  239.         return {
  240.             value: value,
  241.             key: id ? id : 'id',// Must be the key in the Model.
  242.             rules: [{
  243.                 function: 'notEmpty',
  244.                 message: messageEmpty ? messageEmpty : 'An ID is empty.'
  245.             },{
  246.                 function: 'len',
  247.                 message: 'The length of an ID must be '+length+' characters.',
  248.                 args: [length, length]
  249.             }]
  250.         };
  251.     },
  252.  
  253.     /**
  254.      * Default comportment for Label field.
  255.      * @param value
  256.      * @returns {{value: *, key: string, rules: Array}}
  257.      */
  258.     rulesLabel: function(value){
  259.         var minLength = Device.attributes.label.minLength;
  260.         var maxLength = Device.attributes.label.maxLength;
  261.  
  262.         return {
  263.             value: value,
  264.             key: 'label',// Must be the key in the Model.
  265.             rules: [{
  266.                 function: 'notEmpty',
  267.                 message: 'Label is required.'
  268.             },{
  269.                 function: 'len',
  270.                 message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
  271.                 args: [minLength, maxLength]
  272.             }]
  273.         };
  274.     },
  275.  
  276.     /**
  277.      * Default comportment for HardwareId field.
  278.      * @param value
  279.      * @returns {{value: *, key: string, rules: Array}}
  280.      */
  281.     rulesHardwareId: function(value){
  282.         var minLength = Device.attributes.hardwareId.minLength;
  283.         var maxLength = Device.attributes.hardwareId.maxLength;
  284.  
  285.         return {
  286.             value: value,
  287.             key: 'hardwareId',// Must be the key in the Model.
  288.             rules: [{
  289.                 function: 'notEmpty',
  290.                 message: 'Hardware id is required.'
  291.             },{
  292.                 function: 'len',
  293.                 message: 'The min length is '+minLength+'. Max length is '+maxLength+'.',
  294.                 args: [minLength, maxLength]
  295.             }]
  296.         };
  297.     },
  298.  
  299.     /**
  300.      * Default comportment for RefreshFrequency field.
  301.      * @param value
  302.      * @returns {{value: *, key: string, rules: Array}}
  303.      */
  304.     rulesRefreshFrequency: function(value){
  305.         var min = Device.attributes.refreshFrequency.min;
  306.         var max = Device.attributes.refreshFrequency.max;
  307.  
  308.         return {
  309.             value: value,
  310.             key: 'details',// Must be the key in the Model.
  311.             rules: [{
  312.                 function: 'notEmpty',
  313.                 message: 'Frequency is required.'
  314.             },{
  315.                 function: 'min',
  316.                 message: 'The min frequency is '+min+'.',
  317.                 args: [min]
  318.             },{
  319.                 function: 'max',
  320.                 message: 'The max frequency is '+max+'.',
  321.                 args: [max]
  322.             }]
  323.         };
  324.     }
  325. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement