bootstrapValidator.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. /**
  2. * BootstrapValidator (http://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @version v0.3.0
  7. * @author https://twitter.com/nghuuphuoc
  8. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  9. * @license MIT
  10. */
  11. (function($) {
  12. var BootstrapValidator = function(form, options) {
  13. this.$form = $(form);
  14. this.options = $.extend({}, BootstrapValidator.DEFAULT_OPTIONS, options);
  15. this.dfds = {}; // Array of deferred
  16. this.results = {}; // Validating results
  17. this.invalidField = null; // First invalid field
  18. this.$submitButton = null; // The submit button which is clicked to submit form
  19. this._init();
  20. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  21. this.STATUS_VALIDATING = 'VALIDATING';
  22. this.STATUS_INVALID = 'INVALID';
  23. this.STATUS_VALID = 'VALID';
  24. };
  25. // The default options
  26. BootstrapValidator.DEFAULT_OPTIONS = {
  27. // The form CSS class
  28. elementClass: 'bootstrap-validator-form',
  29. // Default invalid message
  30. message: 'This value is not valid',
  31. // The number of grid columns
  32. // Change it if you use custom grid with different number of columns
  33. columns: 12,
  34. // Shows ok/error/loading icons based on the field validity.
  35. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  36. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  37. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  38. //
  39. // Examples:
  40. // - Use Glyphicons icons:
  41. // feedbackIcons: {
  42. // valid: 'glyphicon glyphicon-ok',
  43. // invalid: 'glyphicon glyphicon-remove',
  44. // validating: 'glyphicon glyphicon-refresh'
  45. // }
  46. // - Use FontAwesome icons:
  47. // feedbackIcons: {
  48. // valid: 'fa fa-check',
  49. // invalid: 'fa fa-times',
  50. // validating: 'fa fa-refresh'
  51. // }
  52. feedbackIcons: null,
  53. // The submit buttons selector
  54. // These buttons will be disabled to prevent the valid form from multiple submissions
  55. submitButtons: 'button[type="submit"]',
  56. // The custom submit handler
  57. // It will prevent the form from the default submission
  58. //
  59. // submitHandler: function(validator, form) {
  60. // - validator is the BootstrapValidator instance
  61. // - form is the jQuery object present the current form
  62. // }
  63. submitHandler: null,
  64. // Live validating option
  65. // Can be one of 3 values:
  66. // - enabled: The plugin validates fields as soon as they are changed
  67. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  68. // - submitted: The live validating is enabled after the form is submitted
  69. live: 'enabled',
  70. // Map the field name with validator rules
  71. fields: null
  72. };
  73. BootstrapValidator.prototype = {
  74. constructor: BootstrapValidator,
  75. /**
  76. * Init form
  77. */
  78. _init: function() {
  79. if (this.options.fields == null) {
  80. return;
  81. }
  82. var that = this;
  83. this.$form
  84. // Disable client side validation in HTML 5
  85. .attr('novalidate', 'novalidate')
  86. .addClass(this.options.elementClass)
  87. // Disable the default submission first
  88. .on('submit.bootstrapValidator', function(e) {
  89. e.preventDefault();
  90. that.validate();
  91. })
  92. .find(this.options.submitButtons)
  93. .on('click', function() {
  94. that.$submitButton = $(this);
  95. });
  96. for (var field in this.options.fields) {
  97. this._initField(field);
  98. }
  99. this._setLiveValidating();
  100. },
  101. /**
  102. * Init field
  103. *
  104. * @param {String} field The field name
  105. */
  106. _initField: function(field) {
  107. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  108. return;
  109. }
  110. this.dfds[field] = {};
  111. this.results[field] = {};
  112. var fields = this.getFieldElements(field);
  113. // We don't need to validate ...
  114. if (fields == null // ... non-existing fields
  115. || (fields.length == 1 && fields.is(':disabled'))) // ... disabled field
  116. {
  117. delete this.options.fields[field];
  118. delete this.dfds[field];
  119. return;
  120. }
  121. // Create a help block element for showing the error
  122. var $field = $(fields[0]),
  123. $parent = $field.parents('.form-group'),
  124. // Calculate the number of columns of the label/field element
  125. // Then set offset to the help block element
  126. label, cssClasses, offset, size;
  127. if (label = $parent.find('label').get(0)) {
  128. // The default Bootstrap form don't require class for label (http://getbootstrap.com/css/#forms)
  129. if (cssClasses = $(label).attr('class')) {
  130. cssClasses = cssClasses.split(' ');
  131. for (var i = 0; i < cssClasses.length; i++) {
  132. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i])) {
  133. offset = cssClasses[i].substr(7);
  134. size = cssClasses[i].substr(4, 2);
  135. break;
  136. }
  137. }
  138. }
  139. } else if (cssClasses = $parent.children().eq(0).attr('class')) {
  140. cssClasses = cssClasses.split(' ');
  141. for (var i = 0; i < cssClasses.length; i++) {
  142. if (/^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  143. offset = cssClasses[i].substr(14);
  144. size = cssClasses[i].substr(4, 2);
  145. break;
  146. }
  147. }
  148. }
  149. if (size && offset) {
  150. for (var validatorName in this.options.fields[field].validators) {
  151. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  152. delete this.options.fields[field].validators[validatorName];
  153. continue;
  154. }
  155. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  156. $('<small/>')
  157. .css('display', 'none')
  158. .attr('data-bs-validator', validatorName)
  159. .addClass('help-block')
  160. .addClass(['col-', size, '-offset-', offset].join(''))
  161. .addClass(['col-', size, '-', this.options.columns - offset].join(''))
  162. .appendTo($parent);
  163. }
  164. }
  165. // Prepare the feedback icons
  166. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  167. if (this.options.feedbackIcons) {
  168. $parent.addClass('has-feedback');
  169. $('<i/>').css('display', 'none').addClass('form-control-feedback').insertAfter($(fields[fields.length - 1]));
  170. }
  171. // Whenever the user change the field value, make it as not validated yet
  172. var that = this,
  173. type = fields.attr('type'),
  174. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  175. fields.on(event, function() {
  176. // Whenever the user change the field value, make it as not validated yet
  177. for (var v in that.options.fields[field].validators) {
  178. that.results[field][v] = that.STATUS_NOT_VALIDATED;
  179. }
  180. });
  181. },
  182. /**
  183. * Enable live validating
  184. */
  185. _setLiveValidating: function() {
  186. if ('enabled' == this.options.live) {
  187. var that = this;
  188. for (var field in this.options.fields) {
  189. (function(f) {
  190. var fields = that.getFieldElements(f);
  191. if (fields) {
  192. var type = fields.attr('type'),
  193. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  194. fields.on(event, function() {
  195. that.validateField(f);
  196. });
  197. }
  198. })(field);
  199. }
  200. }
  201. },
  202. /**
  203. * Disable/Enable submit buttons
  204. *
  205. * @param {Boolean} disabled
  206. */
  207. _disableSubmitButtons: function(disabled) {
  208. if (!disabled) {
  209. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  210. } else if (this.options.live != 'disabled') {
  211. // Don't disable if the live validating mode is disabled
  212. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  213. }
  214. },
  215. /**
  216. * Called when all validations are completed
  217. */
  218. _submit: function() {
  219. if (!this.isValid()) {
  220. if ('submitted' == this.options.live) {
  221. this.options.live = 'enabled';
  222. this._setLiveValidating();
  223. }
  224. // Focus to the first invalid field
  225. if (this.invalidField) {
  226. this.getFieldElements(this.invalidField).focus();
  227. }
  228. return;
  229. }
  230. this._disableSubmitButtons(true);
  231. // Call the custom submission if enabled
  232. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  233. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  234. } else {
  235. // Submit form
  236. this.$form.off('submit.bootstrapValidator').submit();
  237. }
  238. },
  239. // --- Public methods ---
  240. /**
  241. * Retrieve the field elements by given name
  242. *
  243. * @param {String} field The field name
  244. * @returns {null|jQuery[]}
  245. */
  246. getFieldElements: function(field) {
  247. var fields = this.$form.find('[name="' + field + '"]');
  248. return (fields.length == 0) ? null : fields;
  249. },
  250. /**
  251. * Validate the form
  252. */
  253. validate: function() {
  254. if (!this.options.fields) {
  255. return this;
  256. }
  257. this._disableSubmitButtons(true);
  258. for (var field in this.options.fields) {
  259. this.validateField(field);
  260. }
  261. this._submit();
  262. return this;
  263. },
  264. /**
  265. * Validate given field
  266. *
  267. * @param {String} field The field name
  268. */
  269. validateField: function(field) {
  270. var that = this,
  271. fields = this.$form.find('[name="' + field + '"]'),
  272. $field = $(fields[0]),
  273. validators = this.options.fields[field].validators,
  274. validatorName,
  275. validateResult;
  276. for (validatorName in validators) {
  277. if (this.dfds[field][validatorName]) {
  278. this.dfds[field][validatorName].reject();
  279. }
  280. // Don't validate field if it is already done
  281. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  282. continue;
  283. }
  284. this.results[field][validatorName] = this.STATUS_VALIDATING;
  285. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  286. if ('object' == typeof validateResult) {
  287. this.updateStatus($field, validatorName, this.STATUS_VALIDATING);
  288. this.dfds[field][validatorName] = validateResult;
  289. validateResult.done(function(isValid, v) {
  290. // v is validator name
  291. delete that.dfds[field][v];
  292. isValid ? that.updateStatus($field, v, that.STATUS_VALID)
  293. : that.updateStatus($field, v, that.STATUS_INVALID);
  294. });
  295. } else if ('boolean' == typeof validateResult) {
  296. validateResult ? this.updateStatus($field, validatorName, this.STATUS_VALID)
  297. : this.updateStatus($field, validatorName, this.STATUS_INVALID);
  298. }
  299. }
  300. },
  301. /**
  302. * Check the form validity
  303. *
  304. * @returns {Boolean}
  305. */
  306. isValid: function() {
  307. var field, validatorName;
  308. for (field in this.results) {
  309. for (validatorName in this.results[field]) {
  310. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  311. return false;
  312. }
  313. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  314. this.invalidField = field;
  315. return false;
  316. }
  317. }
  318. }
  319. return true;
  320. },
  321. /**
  322. * Update field status
  323. *
  324. * @param {jQuery} $field The field element
  325. * @param {String} validatorName
  326. * @param {String} status The status
  327. * Can be STATUS_VALIDATING, STATUS_INVALID, STATUS_VALID
  328. */
  329. updateStatus: function($field, validatorName, status) {
  330. var that = this,
  331. field = $field.attr('name'),
  332. validator = this.options.fields[field].validators[validatorName],
  333. message = validator.message || this.options.message,
  334. $parent = $field.parents('.form-group'),
  335. $errors = $parent.find('.help-block[data-bs-validator]');
  336. switch (status) {
  337. case this.STATUS_VALIDATING:
  338. this.results[field][validatorName] = this.STATUS_VALIDATING;
  339. this._disableSubmitButtons(true);
  340. $parent.removeClass('has-success').removeClass('has-error');
  341. // TODO: Show validating message
  342. $errors.filter('.help-block[data-bs-validator="' + validatorName + '"]').html(message).hide();
  343. if (this.options.feedbackIcons) {
  344. // Show "loading" icon
  345. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  346. }
  347. break;
  348. case this.STATUS_INVALID:
  349. this.results[field][validatorName] = this.STATUS_INVALID;
  350. this._disableSubmitButtons(true);
  351. // Add has-error class to parent element
  352. $parent.removeClass('has-success').addClass('has-error');
  353. $errors.filter('[data-bs-validator="' + validatorName + '"]').html(message).show();
  354. if (this.options.feedbackIcons) {
  355. // Show "error" icon
  356. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  357. }
  358. break;
  359. case this.STATUS_VALID:
  360. this.results[field][validatorName] = this.STATUS_VALID;
  361. // Hide error element
  362. $errors.filter('[data-bs-validator="' + validatorName + '"]').hide();
  363. // If the field is valid
  364. if ($errors.filter(function() {
  365. var display = $(this).css('display'), v = $(this).attr('data-bs-validator');
  366. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  367. }).length == 0
  368. ) {
  369. this._disableSubmitButtons(false);
  370. $parent.removeClass('has-error').addClass('has-success');
  371. // Show the "ok" icon
  372. if (this.options.feedbackIcons) {
  373. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  374. }
  375. }
  376. break;
  377. default:
  378. break;
  379. }
  380. },
  381. // Useful APIs which aren't use internally
  382. /**
  383. * Reset the form
  384. *
  385. * @param {Boolean} resetFormData Reset current form data
  386. */
  387. resetForm: function(resetFormData) {
  388. for (var field in this.options.fields) {
  389. this.dfds[field] = {};
  390. this.results[field] = {};
  391. // Mark all fields as not validated yet
  392. for (var v in this.options.fields[field].validators) {
  393. this.results[field][v] = this.STATUS_NOT_VALIDATED;
  394. }
  395. }
  396. this.invalidField = null;
  397. this.$submitButton = null;
  398. // Hide all error elements
  399. this.$form
  400. .find('.has-error').removeClass('has-error').end()
  401. .find('.has-success').removeClass('has-success').end()
  402. .find('.help-block[data-bs-validator]').hide();
  403. // Enable submit buttons
  404. this._disableSubmitButtons(false);
  405. // Hide all feeback icons
  406. if (this.options.feedbackIcons) {
  407. this.$form.find('.form-control-feedback').removeClass('glyphicon-ok').removeClass('glyphicon-remove').removeClass('glyphicon-refresh').hide();
  408. }
  409. if (resetFormData) {
  410. this.$form.get(0).reset();
  411. }
  412. }
  413. };
  414. // Plugin definition
  415. $.fn.bootstrapValidator = function(options) {
  416. return this.each(function() {
  417. var $this = $(this), data = $this.data('bootstrapValidator');
  418. if (!data) {
  419. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  420. }
  421. if ('string' == typeof options) {
  422. data[options]();
  423. }
  424. });
  425. };
  426. // Available validators
  427. $.fn.bootstrapValidator.validators = {};
  428. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  429. }(window.jQuery));
  430. ;(function($) {
  431. $.fn.bootstrapValidator.validators.between = {
  432. /**
  433. * Return true if the input value is between (strictly or not) two given numbers
  434. *
  435. * @param {BootstrapValidator} validator The validator plugin instance
  436. * @param {jQuery} $field Field element
  437. * @param {Object} options Can consist of the following keys:
  438. * - min
  439. * - max
  440. * - inclusive [optional]: Can be true or false. Default is true
  441. * - message: The invalid message
  442. * @returns {Boolean}
  443. */
  444. validate: function(validator, $field, options) {
  445. var value = $field.val();
  446. if (value == '') {
  447. return true;
  448. }
  449. value = parseFloat(value);
  450. return (options.inclusive === true)
  451. ? (value > options.min && value < options.max)
  452. : (value >= options.min && value <= options.max);
  453. }
  454. };
  455. }(window.jQuery));
  456. ;(function($) {
  457. $.fn.bootstrapValidator.validators.callback = {
  458. /**
  459. * Return result from the callback method
  460. *
  461. * @param {BootstrapValidator} validator The validator plugin instance
  462. * @param {jQuery} $field Field element
  463. * @param {Object} options Can consist of the following keys:
  464. * - callback: The callback method that passes 2 parameters:
  465. * callback: function(fieldValue, validator) {
  466. * // fieldValue is the value of field
  467. * // validator is instance of BootstrapValidator
  468. * }
  469. * - message: The invalid message
  470. * @returns {Boolean|Deferred}
  471. */
  472. validate: function(validator, $field, options) {
  473. var value = $field.val();
  474. if (options.callback && 'function' == typeof options.callback) {
  475. var dfd = new $.Deferred();
  476. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  477. return dfd;
  478. return options.callback.call(this, value, validator);
  479. }
  480. return true;
  481. }
  482. };
  483. }(window.jQuery));
  484. ;(function($) {
  485. $.fn.bootstrapValidator.validators.choice = {
  486. /**
  487. * Check if the number of checked boxes are less or more than a given number
  488. *
  489. * @param {BootstrapValidator} validator The validator plugin instance
  490. * @param {jQuery} $field Field element
  491. * @param {Object} options Consists of following keys:
  492. * - min
  493. * - max
  494. * At least one of two keys is required
  495. * @returns {Boolean}
  496. */
  497. validate: function(validator, $field, options) {
  498. var numChoices = validator
  499. .getFieldElements($field.attr('name'))
  500. .filter(':checked')
  501. .length;
  502. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  503. return false;
  504. }
  505. return true;
  506. }
  507. };
  508. }(window.jQuery));
  509. ;(function($) {
  510. $.fn.bootstrapValidator.validators.creditCard = {
  511. /**
  512. * Return true if the input value is valid credit card number
  513. * Based on https://gist.github.com/DiegoSalazar/4075533
  514. *
  515. * @param {BootstrapValidator} validator The validator plugin instance
  516. * @param {jQuery} $field Field element
  517. * @param {Object} options Can consist of the following key:
  518. * - message: The invalid message
  519. * @returns {Boolean}
  520. */
  521. validate: function(validator, $field, options) {
  522. var value = $field.val();
  523. if (value == '') {
  524. return true;
  525. }
  526. // Accept only digits, dashes or spaces
  527. if (/[^0-9-\s]+/.test(value)) {
  528. return false;
  529. }
  530. // The Luhn Algorithm
  531. // http://en.wikipedia.org/wiki/Luhn
  532. value = value.replace(/\D/g, '');
  533. var check = 0, digit = 0, even = false, length = value.length;
  534. for (var n = length - 1; n >= 0; n--) {
  535. digit = parseInt(value.charAt(n), 10);
  536. if (even) {
  537. if ((digit *= 2) > 9) {
  538. digit -= 9;
  539. }
  540. }
  541. check += digit;
  542. even = !even;
  543. }
  544. return (check % 10) == 0;
  545. }
  546. };
  547. }(window.jQuery));
  548. ;(function($) {
  549. $.fn.bootstrapValidator.validators.different = {
  550. /**
  551. * Return true if the input value is different with given field's value
  552. *
  553. * @param {BootstrapValidator} validator The validator plugin instance
  554. * @param {jQuery} $field Field element
  555. * @param {Object} options Consists of the following key:
  556. * - field: The name of field that will be used to compare with current one
  557. * @returns {Boolean}
  558. */
  559. validate: function(validator, $field, options) {
  560. var value = $field.val();
  561. if (value == '') {
  562. return true;
  563. }
  564. var compareWith = validator.getFieldElements(options.field);
  565. if (compareWith == null) {
  566. return true;
  567. }
  568. if (value != compareWith.val()) {
  569. validator.updateStatus(compareWith, 'different', validator.STATUS_VALID);
  570. return true;
  571. } else {
  572. return false;
  573. }
  574. }
  575. };
  576. }(window.jQuery));
  577. ;(function($) {
  578. $.fn.bootstrapValidator.validators.digits = {
  579. /**
  580. * Return true if the input value contains digits only
  581. *
  582. * @param {BootstrapValidator} validator Validate plugin instance
  583. * @param {jQuery} $field Field element
  584. * @param {Object} options
  585. * @returns {Boolean}
  586. */
  587. validate: function(validator, $field, options) {
  588. var value = $field.val();
  589. if (value == '') {
  590. return true;
  591. }
  592. return /^\d+$/.test(value);
  593. }
  594. }
  595. }(window.jQuery));
  596. ;(function($) {
  597. $.fn.bootstrapValidator.validators.emailAddress = {
  598. /**
  599. * Return true if and only if the input value is a valid email address
  600. *
  601. * @param {BootstrapValidator} validator Validate plugin instance
  602. * @param {jQuery} $field Field element
  603. * @param {Object} options
  604. * @returns {Boolean}
  605. */
  606. validate: function(validator, $field, options) {
  607. var value = $field.val();
  608. if (value == '') {
  609. return true;
  610. }
  611. // Email address regular expression
  612. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  613. var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  614. return emailRegExp.test(value);
  615. }
  616. }
  617. }(window.jQuery));
  618. ;(function($) {
  619. $.fn.bootstrapValidator.validators.greaterThan = {
  620. /**
  621. * Return true if the input value is greater than or equals to given number
  622. *
  623. * @param {BootstrapValidator} validator Validate plugin instance
  624. * @param {jQuery} $field Field element
  625. * @param {Object} options Can consist of the following keys:
  626. * - value: The number used to compare to
  627. * - inclusive [optional]: Can be true or false. Default is true
  628. * - message: The invalid message
  629. * @returns {Boolean}
  630. */
  631. validate: function(validator, $field, options) {
  632. var value = $field.val();
  633. if (value == '') {
  634. return true;
  635. }
  636. value = parseFloat(value);
  637. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  638. }
  639. }
  640. }(window.jQuery));
  641. ;(function($) {
  642. $.fn.bootstrapValidator.validators.hexColor = {
  643. /**
  644. * Return true if the input value is a valid hex color
  645. *
  646. * @param {BootstrapValidator} validator The validator plugin instance
  647. * @param {jQuery} $field Field element
  648. * @param {Object} options Can consist of the following keys:
  649. * - message: The invalid message
  650. * @returns {Boolean}
  651. */
  652. validate: function(validator, $field, options) {
  653. var value = $field.val();
  654. if (value == '') {
  655. return true;
  656. }
  657. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  658. }
  659. };
  660. }(window.jQuery));
  661. ;(function($) {
  662. $.fn.bootstrapValidator.validators.identical = {
  663. /**
  664. * Check if input value equals to value of particular one
  665. *
  666. * @param {BootstrapValidator} validator The validator plugin instance
  667. * @param {jQuery} $field Field element
  668. * @param {Object} options Consists of the following key:
  669. * - field: The name of field that will be used to compare with current one
  670. * @returns {Boolean}
  671. */
  672. validate: function(validator, $field, options) {
  673. var value = $field.val();
  674. if (value == '') {
  675. return true;
  676. }
  677. var compareWith = validator.getFieldElements(options.field);
  678. if (compareWith == null) {
  679. return true;
  680. }
  681. if (value == compareWith.val()) {
  682. validator.updateStatus(compareWith, 'identical', validator.STATUS_VALID);
  683. return true;
  684. } else {
  685. return false;
  686. }
  687. }
  688. };
  689. }(window.jQuery));
  690. ;(function($) {
  691. $.fn.bootstrapValidator.validators.lessThan = {
  692. /**
  693. * Return true if the input value is less than or equal to given number
  694. *
  695. * @param {BootstrapValidator} validator The validator plugin instance
  696. * @param {jQuery} $field Field element
  697. * @param {Object} options Can consist of the following keys:
  698. * - value: The number used to compare to
  699. * - inclusive [optional]: Can be true or false. Default is true
  700. * - message: The invalid message
  701. * @returns {Boolean}
  702. */
  703. validate: function(validator, $field, options) {
  704. var value = $field.val();
  705. if (value == '') {
  706. return true;
  707. }
  708. value = parseFloat(value);
  709. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  710. }
  711. };
  712. }(window.jQuery));
  713. ;(function($) {
  714. $.fn.bootstrapValidator.validators.notEmpty = {
  715. /**
  716. * Check if input value is empty or not
  717. *
  718. * @param {BootstrapValidator} validator The validator plugin instance
  719. * @param {jQuery} $field Field element
  720. * @param {Object} options
  721. * @returns {Boolean}
  722. */
  723. validate: function(validator, $field, options) {
  724. var type = $field.attr('type');
  725. if ('radio' == type || 'checkbox' == type) {
  726. return validator
  727. .getFieldElements($field.attr('name'))
  728. .filter(':checked')
  729. .length > 0;
  730. }
  731. return $.trim($field.val()) != '';
  732. }
  733. };
  734. }(window.jQuery));
  735. ;(function($) {
  736. $.fn.bootstrapValidator.validators.regexp = {
  737. /**
  738. * Check if the element value matches given regular expression
  739. *
  740. * @param {BootstrapValidator} validator The validator plugin instance
  741. * @param {jQuery} $field Field element
  742. * @param {Object} options Consists of the following key:
  743. * - regexp: The regular expression you need to check
  744. * @returns {Boolean}
  745. */
  746. validate: function(validator, $field, options) {
  747. var value = $field.val();
  748. if (value == '') {
  749. return true;
  750. }
  751. return options.regexp.test(value);
  752. }
  753. };
  754. }(window.jQuery));
  755. ;(function($) {
  756. $.fn.bootstrapValidator.validators.remote = {
  757. /**
  758. * Request a remote server to check the input value
  759. *
  760. * @param {BootstrapValidator} validator Plugin instance
  761. * @param {jQuery} $field Field element
  762. * @param {Object} options Can consist of the following keys:
  763. * - url
  764. * - data [optional]: By default, it will take the value
  765. * {
  766. * <fieldName>: <fieldValue>
  767. * }
  768. * - message: The invalid message
  769. * @returns {Boolean|Deferred}
  770. */
  771. validate: function(validator, $field, options) {
  772. var value = $field.val();
  773. if (value == '') {
  774. return true;
  775. }
  776. var name = $field.attr('name'), data = options.data;
  777. if (data == null) {
  778. data = {};
  779. }
  780. // Support dynamic data
  781. if ('function' == typeof data) {
  782. data = data.call(this, validator);
  783. }
  784. data[name] = value;
  785. var dfd = new $.Deferred();
  786. var xhr = $.ajax({
  787. type: 'POST',
  788. url: options.url,
  789. dataType: 'json',
  790. data: data
  791. });
  792. xhr.then(function(response) {
  793. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  794. });
  795. dfd.fail(function() {
  796. xhr.abort();
  797. });
  798. return dfd;
  799. }
  800. };
  801. }(window.jQuery));
  802. ;(function($) {
  803. $.fn.bootstrapValidator.validators.stringLength = {
  804. /**
  805. * Check if the length of element value is less or more than given number
  806. *
  807. * @param {BootstrapValidator} validator The validator plugin instance
  808. * @param {jQuery} $field Field element
  809. * @param {Object} options Consists of following keys:
  810. * - min
  811. * - max
  812. * At least one of two keys is required
  813. * @returns {Boolean}
  814. */
  815. validate: function(validator, $field, options) {
  816. var value = $field.val();
  817. if (value == '') {
  818. return true;
  819. }
  820. var length = $.trim(value).length;
  821. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  822. return false;
  823. }
  824. return true;
  825. }
  826. };
  827. }(window.jQuery));
  828. ;(function($) {
  829. $.fn.bootstrapValidator.validators.uri = {
  830. /**
  831. * Return true if the input value is a valid URL
  832. *
  833. * @param {BootstrapValidator} validator The validator plugin instance
  834. * @param {jQuery} $field Field element
  835. * @param {Object} options
  836. * @returns {Boolean}
  837. */
  838. validate: function(validator, $field, options) {
  839. var value = $field.val();
  840. if (value == '') {
  841. return true;
  842. }
  843. // Credit to https://gist.github.com/dperini/729294
  844. //
  845. // Regular Expression for URL validation
  846. //
  847. // Author: Diego Perini
  848. // Updated: 2010/12/05
  849. //
  850. // the regular expression composed & commented
  851. // could be easily tweaked for RFC compliance,
  852. // it was expressly modified to fit & satisfy
  853. // these test for an URL shortener:
  854. //
  855. // http://mathiasbynens.be/demo/url-regex
  856. //
  857. // Notes on possible differences from a standard/generic validation:
  858. //
  859. // - utf-8 char class take in consideration the full Unicode range
  860. // - TLDs have been made mandatory so single names like "localhost" fails
  861. // - protocols have been restricted to ftp, http and https only as requested
  862. //
  863. // Changes:
  864. //
  865. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  866. // first and last IP address of each class is considered invalid
  867. // (since they are broadcast/network addresses)
  868. //
  869. // - Added exclusion of private, reserved and/or local networks ranges
  870. //
  871. // Compressed one-line versions:
  872. //
  873. // Javascript version
  874. //
  875. // /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i
  876. //
  877. // PHP version
  878. //
  879. // _^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
  880. var urlExp = new RegExp(
  881. "^" +
  882. // protocol identifier
  883. "(?:(?:https?|ftp)://)" +
  884. // user:pass authentication
  885. "(?:\\S+(?::\\S*)?@)?" +
  886. "(?:" +
  887. // IP address exclusion
  888. // private & local networks
  889. "(?!10(?:\\.\\d{1,3}){3})" +
  890. "(?!127(?:\\.\\d{1,3}){3})" +
  891. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  892. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  893. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  894. // IP address dotted notation octets
  895. // excludes loopback network 0.0.0.0
  896. // excludes reserved space >= 224.0.0.0
  897. // excludes network & broacast addresses
  898. // (first & last IP address of each class)
  899. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  900. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  901. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  902. "|" +
  903. // host name
  904. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  905. // domain name
  906. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  907. // TLD identifier
  908. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  909. ")" +
  910. // port number
  911. "(?::\\d{2,5})?" +
  912. // resource path
  913. "(?:/[^\\s]*)?" +
  914. "$", "i"
  915. );
  916. return urlExp.test(value);
  917. }
  918. };
  919. }(window.jQuery));
  920. ;(function($) {
  921. $.fn.bootstrapValidator.validators.zipCode = {
  922. /**
  923. * Return true if and only if the input value is a valid country zip code
  924. *
  925. * @param {BootstrapValidator} validator The validator plugin instance
  926. * @param {jQuery} $field Field element
  927. * @param {Object} options Consist of key:
  928. * - country: The ISO 3166 country code
  929. *
  930. * Currently it supports the following countries:
  931. * - US (United State)
  932. * - DK (Denmark)
  933. * - SE (Sweden)
  934. *
  935. * @returns {Boolean}
  936. */
  937. validate: function(validateInstance, $field, options) {
  938. var value = $field.val();
  939. if (value == '' || !options.country) {
  940. return true;
  941. }
  942. switch (options.country.toUpperCase()) {
  943. case 'DK':
  944. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  945. case 'SE':
  946. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  947. case 'US':
  948. default:
  949. return /^\d{5}([\-]\d{4})?$/.test(value);
  950. }
  951. }
  952. };
  953. }(window.jQuery));