PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/public/altair/bower_components/parsleyjs/src/parsley/validator.js

https://gitlab.com/dima-antonenko/projectX
JavaScript | 287 lines | 212 code | 37 blank | 38 comment | 26 complexity | dfcfd1c6d7ab2de3e553061e7442eaa7 MD5 | raw file
  1. define('parsley/validator', [
  2. 'parsley/defaults',
  3. 'validator'
  4. ], function (ParsleyDefaults, Validator) {
  5. // This is needed for Browserify usage that requires Validator.js through module.exports
  6. Validator = 'undefined' !== typeof Validator ? Validator : ('undefined' !== typeof module ? module.exports : null);
  7. var ParsleyValidator = function (validators, catalog) {
  8. this.__class__ = 'ParsleyValidator';
  9. this.Validator = Validator;
  10. // Default Parsley locale is en
  11. this.locale = 'en';
  12. this.init(validators || {}, catalog || {});
  13. };
  14. ParsleyValidator.prototype = {
  15. init: function (validators, catalog) {
  16. this.catalog = catalog;
  17. // Copy prototype's validators:
  18. this.validators = $.extend({}, this.validators);
  19. for (var name in validators)
  20. this.addValidator(name, validators[name].fn, validators[name].priority, validators[name].requirementsTransformer);
  21. window.Parsley.trigger('parsley:validator:init');
  22. },
  23. // Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
  24. setLocale: function (locale) {
  25. if ('undefined' === typeof this.catalog[locale])
  26. throw new Error(locale + ' is not available in the catalog');
  27. this.locale = locale;
  28. return this;
  29. },
  30. // Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
  31. addCatalog: function (locale, messages, set) {
  32. if ('object' === typeof messages)
  33. this.catalog[locale] = messages;
  34. if (true === set)
  35. return this.setLocale(locale);
  36. return this;
  37. },
  38. // Add a specific message for a given constraint in a given locale
  39. addMessage: function (locale, name, message) {
  40. if ('undefined' === typeof this.catalog[locale])
  41. this.catalog[locale] = {};
  42. this.catalog[locale][name.toLowerCase()] = message;
  43. return this;
  44. },
  45. validate: function (value, constraints, priority) {
  46. return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments);
  47. },
  48. // Add a new validator
  49. addValidator: function (name, fn, priority, requirementsTransformer) {
  50. if (this.validators[name])
  51. ParsleyUtils.warn('Validator "' + name + '" is already defined.');
  52. else if (ParsleyDefaults.hasOwnProperty(name)) {
  53. ParsleyUtils.warn('"' + name + '" is a restricted keyword and is not a valid validator name.');
  54. return;
  55. };
  56. return this._setValidator(name, fn, priority, requirementsTransformer);
  57. },
  58. updateValidator: function (name, fn, priority, requirementsTransformer) {
  59. if (!this.validators[name]) {
  60. ParsleyUtils.warn('Validator "' + name + '" is not already defined.');
  61. return this.addValidator(name, fn, priority, requirementsTransformer);
  62. }
  63. return this._setValidator(name, fn, priority, requirementsTransformer);
  64. },
  65. removeValidator: function (name) {
  66. if (!this.validators[name])
  67. ParsleyUtils.warn('Validator "' + name + '" is not defined.');
  68. delete this.validators[name];
  69. return this;
  70. },
  71. _setValidator: function (name, fn, priority, requirementsTransformer) {
  72. this.validators[name] = function (requirements) {
  73. return $.extend(new Validator.Assert().Callback(fn, requirements), {
  74. priority: priority,
  75. requirementsTransformer: requirementsTransformer
  76. });
  77. };
  78. return this;
  79. },
  80. getErrorMessage: function (constraint) {
  81. var message;
  82. // Type constraints are a bit different, we have to match their requirements too to find right error message
  83. if ('type' === constraint.name) {
  84. var typeMessages = this.catalog[this.locale][constraint.name] || {};
  85. message = typeMessages[constraint.requirements];
  86. } else
  87. message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
  88. return message || this.catalog[this.locale].defaultMessage || this.catalog.en.defaultMessage;
  89. },
  90. // Kind of light `sprintf()` implementation
  91. formatMessage: function (string, parameters) {
  92. if ('object' === typeof parameters) {
  93. for (var i in parameters)
  94. string = this.formatMessage(string, parameters[i]);
  95. return string;
  96. }
  97. return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : '';
  98. },
  99. // Here is the Parsley default validators list.
  100. // This is basically Validatorjs validators, with different API for some of them
  101. // and a Parsley priority set
  102. validators: {
  103. notblank: function () {
  104. return $.extend(new Validator.Assert().NotBlank(), { priority: 2 });
  105. },
  106. required: function () {
  107. return $.extend(new Validator.Assert().Required(), { priority: 512 });
  108. },
  109. type: function (type) {
  110. var assert;
  111. switch (type) {
  112. case 'email':
  113. assert = new Validator.Assert().Email();
  114. break;
  115. // range type just ensure we have a number here
  116. case 'range':
  117. case 'number':
  118. assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$');
  119. break;
  120. case 'integer':
  121. assert = new Validator.Assert().Regexp('^-?\\d+$');
  122. break;
  123. case 'digits':
  124. assert = new Validator.Assert().Regexp('^\\d+$');
  125. break;
  126. case 'alphanum':
  127. assert = new Validator.Assert().Regexp('^\\w+$', 'i');
  128. break;
  129. case 'url':
  130. // Thanks to https://gist.github.com/dperini/729294
  131. // Voted best validator in https://mathiasbynens.be/demo/url-regex
  132. // Modified to make scheme optional and allow local IPs
  133. assert = new Validator.Assert().Regexp(
  134. "^" +
  135. // protocol identifier
  136. "(?:(?:https?|ftp)://)?" + // ** mod: make scheme optional
  137. // user:pass authentication
  138. "(?:\\S+(?::\\S*)?@)?" +
  139. "(?:" +
  140. // IP address exclusion
  141. // private & local networks
  142. // "(?!(?:10|127)(?:\\.\\d{1,3}){3})" + // ** mod: allow local networks
  143. // "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
  144. // "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" + // ** mod: allow local networks
  145. // IP address dotted notation octets
  146. // excludes loopback network 0.0.0.0
  147. // excludes reserved space >= 224.0.0.0
  148. // excludes network & broacast addresses
  149. // (first & last IP address of each class)
  150. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  151. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  152. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  153. "|" +
  154. // host name
  155. "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
  156. // domain name
  157. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
  158. // TLD identifier
  159. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  160. ")" +
  161. // port number
  162. "(?::\\d{2,5})?" +
  163. // resource path
  164. "(?:/\\S*)?" +
  165. "$", 'i');
  166. break;
  167. default:
  168. throw new Error('validator type `' + type + '` is not supported');
  169. }
  170. return $.extend(assert, { priority: 256 });
  171. },
  172. pattern: function (regexp) {
  173. var flags = '';
  174. // Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
  175. if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) {
  176. // Replace the regexp literal string with the first match group: ([gimy]*)
  177. // If no flag is present, this will be a blank string
  178. flags = regexp.replace(/.*\/([gimy]*)$/, '$1');
  179. // Again, replace the regexp literal string with the first match group:
  180. // everything excluding the opening and closing slashes and the flags
  181. regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
  182. }
  183. return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 });
  184. },
  185. minlength: function (value) {
  186. return $.extend(new Validator.Assert().Length({ min: value }), {
  187. priority: 30,
  188. requirementsTransformer: function () {
  189. return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
  190. }
  191. });
  192. },
  193. maxlength: function (value) {
  194. return $.extend(new Validator.Assert().Length({ max: value }), {
  195. priority: 30,
  196. requirementsTransformer: function () {
  197. return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
  198. }
  199. });
  200. },
  201. length: function (array) {
  202. return $.extend(new Validator.Assert().Length({ min: array[0], max: array[1] }), { priority: 32 });
  203. },
  204. mincheck: function (length) {
  205. return this.minlength(length);
  206. },
  207. maxcheck: function (length) {
  208. return this.maxlength(length);
  209. },
  210. check: function (array) {
  211. return this.length(array);
  212. },
  213. min: function (value) {
  214. return $.extend(new Validator.Assert().GreaterThanOrEqual(value), {
  215. priority: 30,
  216. requirementsTransformer: function () {
  217. return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
  218. }
  219. });
  220. },
  221. max: function (value) {
  222. return $.extend(new Validator.Assert().LessThanOrEqual(value), {
  223. priority: 30,
  224. requirementsTransformer: function () {
  225. return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
  226. }
  227. });
  228. },
  229. range: function (array) {
  230. return $.extend(new Validator.Assert().Range(array[0], array[1]), {
  231. priority: 32,
  232. requirementsTransformer: function () {
  233. for (var i = 0; i < array.length; i++)
  234. array[i] = 'string' === typeof array[i] && !isNaN(array[i]) ? parseInt(array[i], 10) : array[i];
  235. return array;
  236. }
  237. });
  238. },
  239. equalto: function (value) {
  240. return $.extend(new Validator.Assert().EqualTo(value), {
  241. priority: 256,
  242. requirementsTransformer: function () {
  243. return $(value).length ? $(value).val() : value;
  244. }
  245. });
  246. }
  247. }
  248. };
  249. return ParsleyValidator;
  250. });