Validator.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var Class = require('./Class');
  2. var keys = require('./keys');
  3. var safeGet = require('./safeGet');
  4. var isFn = require('./isFn');
  5. var isUndef = require('./isUndef');
  6. var isNum = require('./isNum');
  7. var isStr = require('./isStr');
  8. var isBool = require('./isBool');
  9. exports = Class(
  10. {
  11. className: 'Validator',
  12. initialize: function(options) {
  13. this._options = options;
  14. this._optKeys = keys(options);
  15. },
  16. validate: function(obj) {
  17. obj = obj || {};
  18. var options = this._options;
  19. var objKeys = this._optKeys;
  20. for (var i = 0, len = objKeys.length; i < len; i++) {
  21. var key = objKeys[i];
  22. var result = this._validateVal(
  23. safeGet(obj, key),
  24. options[key],
  25. key
  26. );
  27. if (result !== true) return result;
  28. }
  29. return true;
  30. },
  31. _validateVal: function(val, rules, objKey) {
  32. var plugins = exports.plugins;
  33. if (isFn(rules)) return rules(val);
  34. var ruleKeys = keys(rules);
  35. for (var i = 0, len = ruleKeys.length; i < len; i++) {
  36. var key = ruleKeys[i];
  37. var config = rules[key];
  38. var result = true;
  39. if (isFn(config)) result = config(val, objKey);
  40. var plugin = plugins[key];
  41. if (plugin) result = plugin(val, objKey, config);
  42. if (result !== true) return result;
  43. }
  44. return true;
  45. }
  46. },
  47. {
  48. plugins: {
  49. required: function(val, key, config) {
  50. if (config && isUndef(val)) return key + ' is required';
  51. return true;
  52. },
  53. number: function(val, key, config) {
  54. if (config && !isUndef(val) && !isNum(val))
  55. return key + ' should be a number';
  56. return true;
  57. },
  58. boolean: function(val, key, config) {
  59. if (config && !isUndef(val) && !isBool(val))
  60. return key + ' should be a boolean';
  61. return true;
  62. },
  63. string: function(val, key, config) {
  64. if (config && !isUndef(val) && !isStr(val))
  65. return key + ' should be a string';
  66. return true;
  67. },
  68. regexp: function(val, key, config) {
  69. if (isStr(val) && !config.test(val))
  70. return (
  71. key + ' should match given regexp ' + config.toString()
  72. );
  73. return true;
  74. }
  75. },
  76. addPlugin: function(name, plugin) {
  77. exports.plugins[name] = plugin;
  78. }
  79. }
  80. );
  81. module.exports = exports;