bootstrapValidator.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @version v0.4.0-dev
  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. // Shows ok/error/loading icons based on the field validity.
  32. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  33. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  34. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  35. //
  36. // Examples:
  37. // - Use Glyphicons icons:
  38. // feedbackIcons: {
  39. // valid: 'glyphicon glyphicon-ok',
  40. // invalid: 'glyphicon glyphicon-remove',
  41. // validating: 'glyphicon glyphicon-refresh'
  42. // }
  43. // - Use FontAwesome icons:
  44. // feedbackIcons: {
  45. // valid: 'fa fa-check',
  46. // invalid: 'fa fa-times',
  47. // validating: 'fa fa-refresh'
  48. // }
  49. feedbackIcons: {
  50. valid: null,
  51. invalid: null,
  52. validating: null
  53. },
  54. // The submit buttons selector
  55. // These buttons will be disabled to prevent the valid form from multiple submissions
  56. submitButtons: 'button[type="submit"]',
  57. // The custom submit handler
  58. // It will prevent the form from the default submission
  59. //
  60. // submitHandler: function(validator, form) {
  61. // - validator is the BootstrapValidator instance
  62. // - form is the jQuery object present the current form
  63. // }
  64. submitHandler: null,
  65. // Live validating option
  66. // Can be one of 3 values:
  67. // - enabled: The plugin validates fields as soon as they are changed
  68. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  69. // - submitted: The live validating is enabled after the form is submitted
  70. live: 'enabled',
  71. // Map the field name with validator rules
  72. fields: null
  73. };
  74. BootstrapValidator.prototype = {
  75. constructor: BootstrapValidator,
  76. /**
  77. * Init form
  78. */
  79. _init: function() {
  80. var that = this,
  81. options = {
  82. message: this.$form.attr('data-bv-message'),
  83. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  84. live: this.$form.attr('data-bv-live'),
  85. fields: {},
  86. feedbackIcons: {
  87. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  88. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  89. validating: this.$form.attr('data-bv-feedbackicons-validating')
  90. }
  91. },
  92. validator,
  93. i = 0,
  94. v, // Validator name
  95. enabled,
  96. optionName,
  97. optionValue,
  98. html5Attrs;
  99. this.$form
  100. // Disable client side validation in HTML 5
  101. .attr('novalidate', 'novalidate')
  102. .addClass(this.options.elementClass)
  103. // Disable the default submission first
  104. .on('submit.bootstrapValidator', function(e) {
  105. e.preventDefault();
  106. that.validate();
  107. })
  108. .on('click', this.options.submitButtons, function() {
  109. that.$submitButton = $(this);
  110. })
  111. // Find all fields which have either "name" or "data-bv-field" attribute
  112. .find('[name], [data-bv-field]').each(function() {
  113. var $field = $(this),
  114. field = $field.attr('name') || $field.attr('data-bv-field');
  115. $field.attr('data-bv-field', field);
  116. options.fields[field] = $.extend({}, {
  117. message: $field.attr('data-bv-message'),
  118. container: $field.attr('data-bv-container'),
  119. selector: $field.attr('data-bv-selector'),
  120. validators: {}
  121. }, options.fields[field]);
  122. for (v in $.fn.bootstrapValidator.validators) {
  123. validator = $.fn.bootstrapValidator.validators[v];
  124. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  125. html5Attrs = {};
  126. if (('function' == typeof validator.enableByHtml5
  127. && (html5Attrs = validator.enableByHtml5($(this)))
  128. && (enabled != 'false'))
  129. || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
  130. {
  131. // Try to parse the options via attributes
  132. validator.html5Attributes = validator.html5Attributes || ['message'];
  133. options.fields[field]['validators'][v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, options.fields[field]['validators'][v]);
  134. for (i in validator.html5Attributes) {
  135. optionName = validator.html5Attributes[i];
  136. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
  137. if (optionValue) {
  138. if ('true' == optionValue) {
  139. optionValue = true;
  140. } else if ('false' == optionValue) {
  141. optionValue = false;
  142. }
  143. options.fields[field]['validators'][v][optionName] = optionValue;
  144. }
  145. }
  146. }
  147. }
  148. });
  149. this.options = $.extend(true, this.options, options);
  150. //console.log(this.options);
  151. for (var field in this.options.fields) {
  152. this._initField(field);
  153. }
  154. this._setLiveValidating();
  155. },
  156. /**
  157. * Init field
  158. *
  159. * @param {String} field The field name
  160. */
  161. _initField: function(field) {
  162. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  163. return;
  164. }
  165. this.dfds[field] = {};
  166. this.results[field] = {};
  167. var fields = this.getFieldElements(field);
  168. // We don't need to validate non-existing fields
  169. if (fields == null) {
  170. delete this.options.fields[field];
  171. delete this.dfds[field];
  172. return;
  173. }
  174. fields.attr('data-bv-field', field);
  175. // Create help block elements for showing the error messages
  176. var $field = $(fields[0]),
  177. $parent = $field.parents('.form-group'),
  178. // Allow user to indicate where the error messages are shown
  179. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  180. $field.data('bootstrapValidator.messageContainer', $message);
  181. for (var validatorName in this.options.fields[field].validators) {
  182. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  183. delete this.options.fields[field].validators[validatorName];
  184. continue;
  185. }
  186. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  187. $('<small/>')
  188. .css('display', 'none')
  189. .attr('data-bv-validator', validatorName)
  190. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  191. .addClass('help-block')
  192. .appendTo($message);
  193. }
  194. // Prepare the feedback icons
  195. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  196. if (this.options.feedbackIcons
  197. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid)
  198. {
  199. $parent.addClass('has-feedback');
  200. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($(fields[fields.length - 1]));
  201. // The feedback icon does not render correctly if there is no label
  202. // https://github.com/twbs/bootstrap/issues/12873
  203. if ($parent.find('label').length == 0) {
  204. $icon.css('top', 0);
  205. }
  206. }
  207. if (this.options.fields[field]['enabled'] == null) {
  208. this.options.fields[field]['enabled'] = true;
  209. }
  210. // Whenever the user change the field value, mark it as not validated yet
  211. var that = this,
  212. type = fields.attr('type'),
  213. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  214. fields.on(event + '.bootstrapValidator', function() {
  215. that.updateStatus($field, that.STATUS_NOT_VALIDATED, null);
  216. });
  217. },
  218. /**
  219. * Get the element to place the error messages
  220. *
  221. * @param {jQuery} $field The field element
  222. * @returns {jQuery}
  223. */
  224. _getMessageContainer: function($field) {
  225. var $parent = $field.parent();
  226. if ($parent.hasClass('form-group')) {
  227. return $parent;
  228. }
  229. var cssClasses = $parent.attr('class');
  230. if (!cssClasses) {
  231. return this._getMessageContainer($parent);
  232. }
  233. cssClasses = cssClasses.split(' ');
  234. var n = cssClasses.length;
  235. for (var i = 0; i < n; i++) {
  236. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  237. return $parent;
  238. }
  239. }
  240. return this._getMessageContainer($parent);
  241. },
  242. /**
  243. * Enable live validating
  244. */
  245. _setLiveValidating: function() {
  246. if ('enabled' == this.options.live) {
  247. var that = this;
  248. for (var field in this.options.fields) {
  249. (function(f) {
  250. var fields = that.getFieldElements(f);
  251. if (fields) {
  252. var type = fields.attr('type'),
  253. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  254. fields.on(event + '.bootstrapValidator', function() {
  255. that.validateField(f);
  256. });
  257. }
  258. })(field);
  259. }
  260. }
  261. },
  262. /**
  263. * Disable/Enable submit buttons
  264. *
  265. * @param {Boolean} disabled
  266. */
  267. _disableSubmitButtons: function(disabled) {
  268. if (!disabled) {
  269. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  270. } else if (this.options.live != 'disabled') {
  271. // Don't disable if the live validating mode is disabled
  272. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  273. }
  274. },
  275. /**
  276. * Called when all validations are completed
  277. */
  278. _submit: function() {
  279. if (!this.isValid()) {
  280. if ('submitted' == this.options.live) {
  281. this.options.live = 'enabled';
  282. this._setLiveValidating();
  283. }
  284. // Focus to the first invalid field
  285. if (this.invalidField) {
  286. this.getFieldElements(this.invalidField).focus();
  287. }
  288. return;
  289. }
  290. this._disableSubmitButtons(true);
  291. // Call the custom submission if enabled
  292. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  293. // Turn off the submit handler, so user can call form.submit() inside their submitHandler method
  294. this.$form.off('submit.bootstrapValidator');
  295. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  296. } else {
  297. // Submit form
  298. this.$form.off('submit.bootstrapValidator').submit();
  299. }
  300. },
  301. // --- Public methods ---
  302. /**
  303. * Retrieve the field elements by given name
  304. *
  305. * @param {String} field The field name
  306. * @returns {null|jQuery[]}
  307. */
  308. getFieldElements: function(field) {
  309. var fields = this.$form.find(this.options.fields[field].selector || '[name="' + field + '"]');
  310. return (fields.length == 0) ? null : fields;
  311. },
  312. /**
  313. * Validate the form
  314. *
  315. * @return {BootstrapValidator}
  316. */
  317. validate: function() {
  318. if (!this.options.fields) {
  319. return this;
  320. }
  321. this._disableSubmitButtons(true);
  322. for (var field in this.options.fields) {
  323. this.validateField(field);
  324. }
  325. this._submit();
  326. return this;
  327. },
  328. /**
  329. * Validate given field
  330. *
  331. * @param {String} field The field name
  332. */
  333. validateField: function(field) {
  334. if (!this.options.fields[field]['enabled']) {
  335. return;
  336. }
  337. var that = this,
  338. fields = this.getFieldElements(field),
  339. $field = $(fields[0]),
  340. validators = this.options.fields[field].validators,
  341. validatorName,
  342. validateResult;
  343. // We don't need to validate disabled field
  344. if (fields.length == 1 && fields.is(':disabled')) {
  345. delete this.options.fields[field];
  346. delete this.dfds[field];
  347. return;
  348. }
  349. for (validatorName in validators) {
  350. if (this.dfds[field][validatorName]) {
  351. this.dfds[field][validatorName].reject();
  352. }
  353. // Don't validate field if it is already done
  354. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  355. continue;
  356. }
  357. this.results[field][validatorName] = this.STATUS_VALIDATING;
  358. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  359. if ('object' == typeof validateResult) {
  360. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  361. this.dfds[field][validatorName] = validateResult;
  362. validateResult.done(function(isValid, v) {
  363. // v is validator name
  364. delete that.dfds[field][v];
  365. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  366. if (isValid && 'disabled' == that.options.live) {
  367. that._submit();
  368. }
  369. });
  370. } else if ('boolean' == typeof validateResult) {
  371. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  372. }
  373. }
  374. },
  375. /**
  376. * Check the form validity
  377. *
  378. * @returns {Boolean}
  379. */
  380. isValid: function() {
  381. var field, validatorName;
  382. for (field in this.results) {
  383. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  384. continue;
  385. }
  386. for (validatorName in this.results[field]) {
  387. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  388. return false;
  389. }
  390. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  391. this.invalidField = field;
  392. return false;
  393. }
  394. }
  395. }
  396. return true;
  397. },
  398. /**
  399. * Update field status
  400. *
  401. * @param {String|jQuery} field The field name or field element
  402. * @param {String} status The status
  403. * Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  404. * @param {String|null} validatorName The validator name. If null, the method updates validity result for all validators
  405. * @return {BootstrapValidator}
  406. */
  407. updateStatus: function(field, status, validatorName) {
  408. var $field = ('string' == typeof field) ? this.getFieldElements(field) : field,
  409. that = this,
  410. field = $field.attr('data-bv-field'),
  411. $parent = $field.parents('.form-group'),
  412. $message = $field.data('bootstrapValidator.messageContainer'),
  413. $errors = $message.find('.help-block[data-bv-validator]'),
  414. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  415. // Update status
  416. if (validatorName) {
  417. this.results[field][validatorName] = status;
  418. } else {
  419. for (var v in this.options.fields[field].validators) {
  420. this.results[field][v] = status;
  421. }
  422. }
  423. // Show/hide error elements and feedback icons
  424. switch (status) {
  425. case this.STATUS_VALIDATING:
  426. this._disableSubmitButtons(true);
  427. $parent.removeClass('has-success').removeClass('has-error');
  428. // TODO: Show validating message
  429. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  430. if ($icon) {
  431. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  432. }
  433. break;
  434. case this.STATUS_INVALID:
  435. this._disableSubmitButtons(true);
  436. $parent.removeClass('has-success').addClass('has-error');
  437. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  438. if ($icon) {
  439. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  440. }
  441. break;
  442. case this.STATUS_VALID:
  443. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  444. // If the field is valid
  445. if ($errors.filter(function() {
  446. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  447. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  448. }).length == 0
  449. ) {
  450. this._disableSubmitButtons(false);
  451. $parent.removeClass('has-error').addClass('has-success');
  452. if ($icon) {
  453. $icon.removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  454. }
  455. }
  456. break;
  457. case this.STATUS_NOT_VALIDATED:
  458. default:
  459. this._disableSubmitButtons(false);
  460. $parent.removeClass('has-success').removeClass('has-error');
  461. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  462. if ($icon) {
  463. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  464. }
  465. break;
  466. }
  467. return this;
  468. },
  469. // Useful APIs which aren't used internally
  470. /**
  471. * Reset the form
  472. *
  473. * @param {Boolean} resetFormData Reset current form data
  474. * @return {BootstrapValidator}
  475. */
  476. resetForm: function(resetFormData) {
  477. var field, $field, type;
  478. for (field in this.options.fields) {
  479. this.dfds[field] = {};
  480. this.results[field] = {};
  481. $field = this.getFieldElements(field);
  482. // Mark field as not validated yet
  483. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  484. if (resetFormData) {
  485. type = $field.attr('type');
  486. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  487. }
  488. }
  489. this.invalidField = null;
  490. this.$submitButton = null;
  491. // Enable submit buttons
  492. this._disableSubmitButtons(false);
  493. return this;
  494. },
  495. /**
  496. * Enable/Disable all validators to given field
  497. *
  498. * @param {String} field The field name
  499. * @param {Boolean} enabled Enable/Disable field validators
  500. * @return {BootstrapValidator}
  501. */
  502. enableFieldValidators: function(field, enabled) {
  503. this.options.fields[field]['enabled'] = enabled;
  504. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  505. return this;
  506. }
  507. };
  508. // Plugin definition
  509. $.fn.bootstrapValidator = function(options) {
  510. return this.each(function() {
  511. var $this = $(this), data = $this.data('bootstrapValidator');
  512. if (!data) {
  513. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  514. }
  515. if ('string' == typeof options) {
  516. data[options]();
  517. }
  518. });
  519. };
  520. // Available validators
  521. $.fn.bootstrapValidator.validators = {};
  522. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  523. }(window.jQuery));
  524. ;(function($) {
  525. $.fn.bootstrapValidator.validators.base64 = {
  526. /**
  527. * Return true if the input value is a base 64 encoded string.
  528. *
  529. * @param {BootstrapValidator} validator The validator plugin instance
  530. * @param {jQuery} $field Field element
  531. * @param {Object} options Can consist of the following keys:
  532. * - message: The invalid message
  533. * @returns {Boolean}
  534. */
  535. validate: function(validator, $field, options) {
  536. var value = $field.val();
  537. if (value == '') {
  538. return true;
  539. }
  540. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
  541. }
  542. };
  543. }(window.jQuery));
  544. ;(function($) {
  545. $.fn.bootstrapValidator.validators.between = {
  546. /**
  547. * Return true if the input value is between (strictly or not) two given numbers
  548. *
  549. * @param {BootstrapValidator} validator The validator plugin instance
  550. * @param {jQuery} $field Field element
  551. * @param {Object} options Can consist of the following keys:
  552. * - min
  553. * - max
  554. * - inclusive [optional]: Can be true or false. Default is true
  555. * - message: The invalid message
  556. * @returns {Boolean}
  557. */
  558. validate: function(validator, $field, options) {
  559. var value = $field.val();
  560. if (value == '') {
  561. return true;
  562. }
  563. value = parseFloat(value);
  564. return (options.inclusive === true)
  565. ? (value > options.min && value < options.max)
  566. : (value >= options.min && value <= options.max);
  567. }
  568. };
  569. }(window.jQuery));
  570. ;(function($) {
  571. $.fn.bootstrapValidator.validators.callback = {
  572. /**
  573. * Return result from the callback method
  574. *
  575. * @param {BootstrapValidator} validator The validator plugin instance
  576. * @param {jQuery} $field Field element
  577. * @param {Object} options Can consist of the following keys:
  578. * - callback: The callback method that passes 2 parameters:
  579. * callback: function(fieldValue, validator) {
  580. * // fieldValue is the value of field
  581. * // validator is instance of BootstrapValidator
  582. * }
  583. * - message: The invalid message
  584. * @returns {Boolean|Deferred}
  585. */
  586. validate: function(validator, $field, options) {
  587. var value = $field.val();
  588. if (options.callback && 'function' == typeof options.callback) {
  589. var dfd = new $.Deferred();
  590. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  591. return dfd;
  592. }
  593. return true;
  594. }
  595. };
  596. }(window.jQuery));
  597. ;(function($) {
  598. $.fn.bootstrapValidator.validators.choice = {
  599. html5Attributes: ['message', 'min', 'max'],
  600. /**
  601. * Check if the number of checked boxes are less or more than a given number
  602. *
  603. * @param {BootstrapValidator} validator The validator plugin instance
  604. * @param {jQuery} $field Field element
  605. * @param {Object} options Consists of following keys:
  606. * - min
  607. * - max
  608. * At least one of two keys is required
  609. * @returns {Boolean}
  610. */
  611. validate: function(validator, $field, options) {
  612. var numChoices = validator
  613. .getFieldElements($field.attr('data-bv-field'))
  614. .filter(':checked')
  615. .length;
  616. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  617. return false;
  618. }
  619. return true;
  620. }
  621. };
  622. }(window.jQuery));
  623. ;(function($) {
  624. $.fn.bootstrapValidator.validators.creditCard = {
  625. /**
  626. * Return true if the input value is valid credit card number
  627. * Based on https://gist.github.com/DiegoSalazar/4075533
  628. *
  629. * @param {BootstrapValidator} validator The validator plugin instance
  630. * @param {jQuery} $field Field element
  631. * @param {Object} options Can consist of the following key:
  632. * - message: The invalid message
  633. * @returns {Boolean}
  634. */
  635. validate: function(validator, $field, options) {
  636. var value = $field.val();
  637. if (value == '') {
  638. return true;
  639. }
  640. // Accept only digits, dashes or spaces
  641. if (/[^0-9-\s]+/.test(value)) {
  642. return false;
  643. }
  644. value = value.replace(/\D/g, '');
  645. // Validate the check sum
  646. // The Luhn Algorithm
  647. // http://en.wikipedia.org/wiki/Luhn
  648. var check = 0, digit = 0, even = false, length = value.length;
  649. for (var n = length - 1; n >= 0; n--) {
  650. digit = parseInt(value.charAt(n), 10);
  651. if (even) {
  652. if ((digit *= 2) > 9) {
  653. digit -= 9;
  654. }
  655. }
  656. check += digit;
  657. even = !even;
  658. }
  659. if ((check % 10) != 0) {
  660. return false;
  661. }
  662. // Validate the card number based on prefix (IIN ranges) and length
  663. var cards = {
  664. AMERICAN_EXPRESS: {
  665. length: [15],
  666. prefix: ['34', '37']
  667. },
  668. DINERS_CLUB: {
  669. length: [14],
  670. prefix: ['300', '301', '302', '303', '304', '305', '36']
  671. },
  672. DINERS_CLUB_US: {
  673. length: [16],
  674. prefix: ['54', '55']
  675. },
  676. DISCOVER: {
  677. length: [16],
  678. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  679. '62214', '62215', '62216', '62217', '62218', '62219',
  680. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  681. '62290', '62291', '622920', '622921', '622922', '622923',
  682. '622924', '622925', '644', '645', '646', '647', '648',
  683. '649', '65']
  684. },
  685. JCB: {
  686. length: [16],
  687. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  688. },
  689. LASER: {
  690. length: [16, 17, 18, 19],
  691. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  692. },
  693. MAESTRO: {
  694. length: [12, 13, 14, 15, 16, 17, 18, 19],
  695. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  696. },
  697. MASTERCARD: {
  698. length: [16],
  699. prefix: ['51', '52', '53', '54', '55']
  700. },
  701. SOLO: {
  702. length: [16, 18, 19],
  703. prefix: ['6334', '6767']
  704. },
  705. UNIONPAY: {
  706. length: [16, 17, 18, 19],
  707. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  708. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  709. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  710. '622920', '622921', '622922', '622923', '622924', '622925']
  711. },
  712. VISA: {
  713. length: [16],
  714. prefix: ['4']
  715. }
  716. };
  717. var type, i;
  718. for (type in cards) {
  719. for (i in cards[type]['prefix']) {
  720. if (value.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  721. && cards[type]['length'].indexOf(value.length) != -1) // and length
  722. {
  723. return true;
  724. }
  725. }
  726. }
  727. return false;
  728. }
  729. };
  730. }(window.jQuery));
  731. ;(function($) {
  732. $.fn.bootstrapValidator.validators.cvv = {
  733. /**
  734. * Return true if the input value is a valid CVV number.
  735. *
  736. * @param {BootstrapValidator} validator The validator plugin instance
  737. * @param {jQuery} $field Field element
  738. * @param {Object} options Can consist of the following keys:
  739. * - creditCardField: The credit card number field. It can be null
  740. * - message: The invalid message
  741. * @returns {Boolean}
  742. */
  743. validate: function(validator, $field, options) {
  744. var value = $field.val();
  745. if (value == '') {
  746. return true;
  747. }
  748. if (!/^[0-9]{3,4}$/.test(value)) {
  749. return false;
  750. }
  751. if (!options.creditCardField) {
  752. return true;
  753. }
  754. // Get the credit card number
  755. var creditCard = validator.getFieldElements(options.creditCardField).val();
  756. if (creditCard == '') {
  757. return true;
  758. }
  759. // Supported credit card types
  760. var cards = {
  761. AMERICAN_EXPRESS: {
  762. length: [15],
  763. prefix: ['34', '37']
  764. },
  765. DINERS_CLUB: {
  766. length: [14],
  767. prefix: ['300', '301', '302', '303', '304', '305', '36']
  768. },
  769. DINERS_CLUB_US: {
  770. length: [16],
  771. prefix: ['54', '55']
  772. },
  773. DISCOVER: {
  774. length: [16],
  775. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  776. '62214', '62215', '62216', '62217', '62218', '62219',
  777. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  778. '62290', '62291', '622920', '622921', '622922', '622923',
  779. '622924', '622925', '644', '645', '646', '647', '648',
  780. '649', '65']
  781. },
  782. JCB: {
  783. length: [16],
  784. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  785. },
  786. LASER: {
  787. length: [16, 17, 18, 19],
  788. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  789. },
  790. MAESTRO: {
  791. length: [12, 13, 14, 15, 16, 17, 18, 19],
  792. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  793. },
  794. MASTERCARD: {
  795. length: [16],
  796. prefix: ['51', '52', '53', '54', '55']
  797. },
  798. SOLO: {
  799. length: [16, 18, 19],
  800. prefix: ['6334', '6767']
  801. },
  802. UNIONPAY: {
  803. length: [16, 17, 18, 19],
  804. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  805. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  806. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  807. '622920', '622921', '622922', '622923', '622924', '622925']
  808. },
  809. VISA: {
  810. length: [16],
  811. prefix: ['4']
  812. }
  813. };
  814. var type, i, creditCardType = null;
  815. for (type in cards) {
  816. for (i in cards[type]['prefix']) {
  817. if (creditCard.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  818. && cards[type]['length'].indexOf(creditCard.length) != -1) // and length
  819. {
  820. creditCardType = type;
  821. break;
  822. }
  823. }
  824. }
  825. return (creditCardType == null)
  826. ? false
  827. : (('AMERICAN_EXPRESS' == creditCardType) ? (value.length == 4) : (value.length == 3));
  828. }
  829. };
  830. }(window.jQuery));
  831. ;(function($) {
  832. $.fn.bootstrapValidator.validators.date = {
  833. html5Attributes: ['message', 'format'],
  834. /**
  835. * Return true if the input value is valid date
  836. *
  837. * @param {BootstrapValidator} validator The validator plugin instance
  838. * @param {jQuery} $field Field element
  839. * @param {Object} options Can consist of the following keys:
  840. * - format: The date format. Default is MM/DD/YYYY
  841. * Support the following formats:
  842. * YYYY/DD/MM
  843. * YYYY/DD/MM h:m A
  844. * YYYY/MM/DD
  845. * YYYY/MM/DD h:m A
  846. *
  847. * YYYY-DD-MM
  848. * YYYY-DD-MM h:m A
  849. * YYYY-MM-DD
  850. * YYYY-MM-DD h:m A
  851. *
  852. * MM/DD/YYYY
  853. * MM/DD/YYYY h:m A
  854. * DD/MM/YYYY
  855. * DD/MM/YYYY h:m A
  856. *
  857. * MM-DD-YYYY
  858. * MM-DD-YYYY h:m A
  859. * DD-MM-YYYY
  860. * DD-MM-YYYY h:m A
  861. * - message: The invalid message
  862. * @returns {Boolean}
  863. */
  864. validate: function(validator, $field, options) {
  865. var value = $field.val();
  866. if (value == '') {
  867. return true;
  868. }
  869. // Determine the separator
  870. options.format = options.format || 'MM/DD/YYYY';
  871. var separator = (options.format.indexOf('/') != -1)
  872. ? '/'
  873. : ((options.format.indexOf('-') != -1) ? '-' : null);
  874. if (separator == null) {
  875. return false;
  876. }
  877. var month, day, year, minutes = null, hours = null, matches;
  878. switch (true) {
  879. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  880. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  881. year = matches[1]; day = matches[2]; month = matches[3];
  882. break;
  883. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  884. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  885. day = matches[1]; month = matches[2]; year = matches[3];
  886. break;
  887. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  888. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  889. year = matches[1]; month = matches[2]; day = matches[3];
  890. break;
  891. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  892. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  893. month = matches[1]; day = matches[2]; year = matches[3];
  894. break;
  895. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/DD/MM h:m A'):
  896. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-DD-MM h:m A'):
  897. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  898. break;
  899. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD/MM/YYYY h:m A'):
  900. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD-MM-YYYY h:m A'):
  901. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  902. break;
  903. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/MM/DD h:m A'):
  904. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-MM-DD h:m A'):
  905. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  906. break;
  907. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM/DD/YYYY h:m A'):
  908. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM-DD-YYYY h:m A'):
  909. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  910. break;
  911. default:
  912. return false;
  913. }
  914. // Validate hours and minutes
  915. if (hours && minutes) {
  916. hours = parseInt(hours, 10);
  917. minutes = parseInt(minutes, 10);
  918. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  919. return false;
  920. }
  921. }
  922. // Validate day, month, and year
  923. day = parseInt(day, 10);
  924. month = parseInt(month, 10);
  925. year = parseInt(year, 10);
  926. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  927. return false;
  928. }
  929. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  930. // Update the number of days in Feb of leap year
  931. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  932. numDays[1] = 29;
  933. }
  934. // Check the day
  935. return (day > 0 && day <= numDays[month - 1]);
  936. }
  937. };
  938. }(window.jQuery));
  939. ;(function($) {
  940. $.fn.bootstrapValidator.validators.different = {
  941. html5Attributes: ['message', 'field'],
  942. /**
  943. * Return true if the input value is different with given field's value
  944. *
  945. * @param {BootstrapValidator} validator The validator plugin instance
  946. * @param {jQuery} $field Field element
  947. * @param {Object} options Consists of the following key:
  948. * - field: The name of field that will be used to compare with current one
  949. * - message: The invalid message
  950. * @returns {Boolean}
  951. */
  952. validate: function(validator, $field, options) {
  953. var value = $field.val();
  954. if (value == '') {
  955. return true;
  956. }
  957. var compareWith = validator.getFieldElements(options.field);
  958. if (compareWith == null) {
  959. return true;
  960. }
  961. if (value != compareWith.val()) {
  962. validator.updateStatus(compareWith, validator.STATUS_VALID, 'different');
  963. return true;
  964. } else {
  965. return false;
  966. }
  967. }
  968. };
  969. }(window.jQuery));
  970. ;(function($) {
  971. $.fn.bootstrapValidator.validators.digits = {
  972. /**
  973. * Return true if the input value contains digits only
  974. *
  975. * @param {BootstrapValidator} validator Validate plugin instance
  976. * @param {jQuery} $field Field element
  977. * @param {Object} options
  978. * @returns {Boolean}
  979. */
  980. validate: function(validator, $field, options) {
  981. var value = $field.val();
  982. if (value == '') {
  983. return true;
  984. }
  985. return /^\d+$/.test(value);
  986. }
  987. }
  988. }(window.jQuery));
  989. ;(function($) {
  990. $.fn.bootstrapValidator.validators.emailAddress = {
  991. enableByHtml5: function($field) {
  992. return ('email' == $field.attr('type'));
  993. },
  994. /**
  995. * Return true if and only if the input value is a valid email address
  996. *
  997. * @param {BootstrapValidator} validator Validate plugin instance
  998. * @param {jQuery} $field Field element
  999. * @param {Object} options
  1000. * @returns {Boolean}
  1001. */
  1002. validate: function(validator, $field, options) {
  1003. var value = $field.val();
  1004. if (value == '') {
  1005. return true;
  1006. }
  1007. // Email address regular expression
  1008. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  1009. 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,}))$/;
  1010. return emailRegExp.test(value);
  1011. }
  1012. }
  1013. }(window.jQuery));
  1014. ;(function($) {
  1015. $.fn.bootstrapValidator.validators.greaterThan = {
  1016. /**
  1017. * Return true if the input value is greater than or equals to given number
  1018. *
  1019. * @param {BootstrapValidator} validator Validate plugin instance
  1020. * @param {jQuery} $field Field element
  1021. * @param {Object} options Can consist of the following keys:
  1022. * - value: The number used to compare to
  1023. * - inclusive [optional]: Can be true or false. Default is true
  1024. * - message: The invalid message
  1025. * @returns {Boolean}
  1026. */
  1027. validate: function(validator, $field, options) {
  1028. var value = $field.val();
  1029. if (value == '') {
  1030. return true;
  1031. }
  1032. value = parseFloat(value);
  1033. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  1034. }
  1035. }
  1036. }(window.jQuery));
  1037. ;(function($) {
  1038. $.fn.bootstrapValidator.validators.hexColor = {
  1039. /**
  1040. * Return true if the input value is a valid hex color
  1041. *
  1042. * @param {BootstrapValidator} validator The validator plugin instance
  1043. * @param {jQuery} $field Field element
  1044. * @param {Object} options Can consist of the following keys:
  1045. * - message: The invalid message
  1046. * @returns {Boolean}
  1047. */
  1048. validate: function(validator, $field, options) {
  1049. var value = $field.val();
  1050. if (value == '') {
  1051. return true;
  1052. }
  1053. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  1054. }
  1055. };
  1056. }(window.jQuery));
  1057. ;(function($) {
  1058. $.fn.bootstrapValidator.validators.identical = {
  1059. html5Attributes: ['message', 'field'],
  1060. /**
  1061. * Check if input value equals to value of particular one
  1062. *
  1063. * @param {BootstrapValidator} validator The validator plugin instance
  1064. * @param {jQuery} $field Field element
  1065. * @param {Object} options Consists of the following key:
  1066. * - field: The name of field that will be used to compare with current one
  1067. * @returns {Boolean}
  1068. */
  1069. validate: function(validator, $field, options) {
  1070. var value = $field.val();
  1071. if (value == '') {
  1072. return true;
  1073. }
  1074. var compareWith = validator.getFieldElements(options.field);
  1075. if (compareWith == null) {
  1076. return true;
  1077. }
  1078. if (value == compareWith.val()) {
  1079. validator.updateStatus(compareWith, validator.STATUS_VALID, 'identical');
  1080. return true;
  1081. } else {
  1082. return false;
  1083. }
  1084. }
  1085. };
  1086. }(window.jQuery));
  1087. ;(function($) {
  1088. $.fn.bootstrapValidator.validators.ip = {
  1089. html5Attributes: ['message', 'ipv4', 'ipv6'],
  1090. /**
  1091. * Return true if the input value is a IP address.
  1092. *
  1093. * @param {BootstrapValidator} validator The validator plugin instance
  1094. * @param {jQuery} $field Field element
  1095. * @param {Object} options Can consist of the following keys:
  1096. * - ipv4: Enable IPv4 validator, default to true
  1097. * - ipv6: Enable IPv6 validator, default to true
  1098. * - message: The invalid message
  1099. * @returns {Boolean}
  1100. */
  1101. validate: function(validator, $field, options) {
  1102. var value = $field.val();
  1103. if (value == '') {
  1104. return true;
  1105. }
  1106. options = $.extend({}, { ipv4: true, ipv6: true }, options);
  1107. if (options.ipv4) {
  1108. return /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value);
  1109. } else if (options.ipv6) {
  1110. return /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(str);
  1111. }
  1112. return false;
  1113. }
  1114. };
  1115. }(window.jQuery));
  1116. ;(function($) {
  1117. $.fn.bootstrapValidator.validators.isbn = {
  1118. /**
  1119. * Return true if the input value is a valid ISBN 10 or ISBN 13 number
  1120. *
  1121. * @param {BootstrapValidator} validator The validator plugin instance
  1122. * @param {jQuery} $field Field element
  1123. * @param {Object} options Can consist of the following keys:
  1124. * - message: The invalid message
  1125. * @returns {Boolean}
  1126. */
  1127. validate: function(validator, $field, options) {
  1128. var value = $field.val();
  1129. if (value == '') {
  1130. return true;
  1131. }
  1132. // Replace all special characters except digits and X
  1133. value = value.replace(/[^\dX]/gi, '');
  1134. var chars = value.split(''),
  1135. sum = 0,
  1136. checksum;
  1137. // See http://en.wikipedia.org/wiki/International_Standard_Book_Number
  1138. switch (chars.length) {
  1139. // ISBN 10
  1140. case 10:
  1141. sum = 0;
  1142. for (var i = 0; i < 9; i++) {
  1143. sum += ((10 - i) * parseInt(chars[i]));
  1144. }
  1145. checksum = 11 - (sum % 11);
  1146. if (checksum == 11) {
  1147. checksum = 0;
  1148. } else if (checksum == 10) {
  1149. checksum = 'X';
  1150. }
  1151. return (checksum == chars[9]);
  1152. // ISBN 13
  1153. case 13:
  1154. sum = 0;
  1155. for (var i = 0; i < 12; i++) {
  1156. sum += ((i % 2 == 0) ? parseInt(chars[i]) : (parseInt(chars[i]) * 3));
  1157. }
  1158. checksum = 10 - (sum % 10);
  1159. if (checksum == 10) {
  1160. checksum = '0';
  1161. }
  1162. return (checksum == chars[12]);
  1163. default:
  1164. return false;
  1165. }
  1166. }
  1167. };
  1168. }(window.jQuery));
  1169. ;(function($) {
  1170. $.fn.bootstrapValidator.validators.lessThan = {
  1171. html5Attributes: ['message', 'value', 'inclusive'],
  1172. enableByHtml5: function($field) {
  1173. var max = $field.attr('max');
  1174. if (max) {
  1175. return {
  1176. value: max
  1177. };
  1178. }
  1179. return false;
  1180. },
  1181. /**
  1182. * Return true if the input value is less than or equal to given number
  1183. *
  1184. * @param {BootstrapValidator} validator The validator plugin instance
  1185. * @param {jQuery} $field Field element
  1186. * @param {Object} options Can consist of the following keys:
  1187. * - value: The number used to compare to
  1188. * - inclusive [optional]: Can be true or false. Default is true
  1189. * - message: The invalid message
  1190. * @returns {Boolean}
  1191. */
  1192. validate: function(validator, $field, options) {
  1193. var value = $field.val();
  1194. if (value == '') {
  1195. return true;
  1196. }
  1197. value = parseFloat(value);
  1198. return (options.inclusive === false) ? (value <= options.value) : (value < options.value);
  1199. }
  1200. };
  1201. }(window.jQuery));
  1202. ;(function($) {
  1203. $.fn.bootstrapValidator.validators.mac = {
  1204. /**
  1205. * Return true if the input value is a MAC address.
  1206. *
  1207. * @param {BootstrapValidator} validator The validator plugin instance
  1208. * @param {jQuery} $field Field element
  1209. * @param {Object} options Can consist of the following keys:
  1210. * - message: The invalid message
  1211. * @returns {Boolean}
  1212. */
  1213. validate: function(validator, $field, options) {
  1214. var value = $field.val();
  1215. if (value == '') {
  1216. return true;
  1217. }
  1218. return /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(value);
  1219. }
  1220. };
  1221. }(window.jQuery));
  1222. ;(function($) {
  1223. $.fn.bootstrapValidator.validators.notEmpty = {
  1224. enableByHtml5: function($field) {
  1225. var required = $field.attr('required') + '';
  1226. return ('required' == required || 'true' == required);
  1227. },
  1228. /**
  1229. * Check if input value is empty or not
  1230. *
  1231. * @param {BootstrapValidator} validator The validator plugin instance
  1232. * @param {jQuery} $field Field element
  1233. * @param {Object} options
  1234. * @returns {Boolean}
  1235. */
  1236. validate: function(validator, $field, options) {
  1237. var type = $field.attr('type');
  1238. if ('radio' == type || 'checkbox' == type) {
  1239. return validator
  1240. .getFieldElements($field.attr('data-bv-field'))
  1241. .filter(':checked')
  1242. .length > 0;
  1243. }
  1244. return $.trim($field.val()) != '';
  1245. }
  1246. };
  1247. }(window.jQuery));
  1248. ;(function($) {
  1249. $.fn.bootstrapValidator.validators.phone = {
  1250. html5Attributes: ['message', 'country'],
  1251. /**
  1252. * Return true if the input value contains a valid US phone number only
  1253. *
  1254. * @param {BootstrapValidator} validator Validate plugin instance
  1255. * @param {jQuery} $field Field element
  1256. * @param {Object} options Consist of key:
  1257. * - message: The invalid message
  1258. * - country: The ISO 3166 country code
  1259. * Currently it only supports United State (US) country
  1260. * @returns {Boolean}
  1261. */
  1262. validate: function(validator, $field, options) {
  1263. var value = $field.val();
  1264. if (value == '') {
  1265. return true;
  1266. }
  1267. options.country = options.country || 'US';
  1268. switch (options.country.toUpperCase()) {
  1269. case 'US':
  1270. default:
  1271. value = value.replace(/\(|\)|\s+/g, '');
  1272. return (/^(?:1\-?)?(\d{3})[\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value);
  1273. }
  1274. }
  1275. }
  1276. }(window.jQuery));
  1277. ;(function($) {
  1278. $.fn.bootstrapValidator.validators.regexp = {
  1279. html5Attributes: ['message', 'regexp'],
  1280. enableByHtml5: function($field) {
  1281. var pattern = $field.attr('pattern');
  1282. if (pattern) {
  1283. return {
  1284. regexp: pattern
  1285. };
  1286. }
  1287. return false;
  1288. },
  1289. /**
  1290. * Check if the element value matches given regular expression
  1291. *
  1292. * @param {BootstrapValidator} validator The validator plugin instance
  1293. * @param {jQuery} $field Field element
  1294. * @param {Object} options Consists of the following key:
  1295. * - regexp: The regular expression you need to check
  1296. * @returns {Boolean}
  1297. */
  1298. validate: function(validator, $field, options) {
  1299. var value = $field.val();
  1300. if (value == '') {
  1301. return true;
  1302. }
  1303. var regexp = ('string' == typeof options.regexp) ? new RegExp(options.regexp) : options.regexp;
  1304. return regexp.test(value);
  1305. }
  1306. };
  1307. }(window.jQuery));
  1308. ;(function($) {
  1309. $.fn.bootstrapValidator.validators.remote = {
  1310. html5Attributes: ['message', 'url'],
  1311. /**
  1312. * Request a remote server to check the input value
  1313. *
  1314. * @param {BootstrapValidator} validator Plugin instance
  1315. * @param {jQuery} $field Field element
  1316. * @param {Object} options Can consist of the following keys:
  1317. * - url
  1318. * - data [optional]: By default, it will take the value
  1319. * {
  1320. * <fieldName>: <fieldValue>
  1321. * }
  1322. * - message: The invalid message
  1323. * @returns {Boolean|Deferred}
  1324. */
  1325. validate: function(validator, $field, options) {
  1326. var value = $field.val();
  1327. if (value == '') {
  1328. return true;
  1329. }
  1330. var name = $field.attr('data-bv-field'), data = options.data;
  1331. if (data == null) {
  1332. data = {};
  1333. }
  1334. // Support dynamic data
  1335. if ('function' == typeof data) {
  1336. data = data.call(this, validator);
  1337. }
  1338. data[name] = value;
  1339. var dfd = new $.Deferred();
  1340. var xhr = $.ajax({
  1341. type: 'POST',
  1342. url: options.url,
  1343. dataType: 'json',
  1344. data: data
  1345. });
  1346. xhr.then(function(response) {
  1347. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  1348. });
  1349. dfd.fail(function() {
  1350. xhr.abort();
  1351. });
  1352. return dfd;
  1353. }
  1354. };
  1355. }(window.jQuery));
  1356. ;(function($) {
  1357. $.fn.bootstrapValidator.validators.step = {
  1358. /**
  1359. * Return true if the input value is valid step one
  1360. *
  1361. * @param {BootstrapValidator} validator The validator plugin instance
  1362. * @param {jQuery} $field Field element
  1363. * @param {Object} options Can consist of the following keys:
  1364. * - baseValue: The base value
  1365. * - step: The step
  1366. * - message: The invalid message
  1367. * @returns {Boolean}
  1368. */
  1369. validate: function(validator, $field, options) {
  1370. var value = $field.val();
  1371. if (value == '') {
  1372. return true;
  1373. }
  1374. options = $.extend({}, { baseValue: 0, step: 1 }, options);
  1375. value = parseFloat(value);
  1376. if (isNaN(value) || !isFinite(value)) {
  1377. return false;
  1378. }
  1379. var round = function(x, precision) {
  1380. var m = Math.pow(10, precision);
  1381. x = x * m;
  1382. var sign = (x > 0) | -(x < 0),
  1383. isHalf = (x % 1 === 0.5 * sign);
  1384. if (isHalf) {
  1385. return (Math.floor(x) + (sign > 0)) / m;
  1386. } else {
  1387. return Math.round(x) / m;
  1388. }
  1389. },
  1390. floatMod = function(x, y) {
  1391. if (y == 0.0) {
  1392. return 1.0;
  1393. }
  1394. var dotX = (x + '').split('.'),
  1395. dotY = (y + '').split('.'),
  1396. precision = ((dotX.length == 1) ? 0 : dotX[1].length) + ((dotY.length == 1) ? 0 : dotY[1].length);
  1397. return round(x - y * Math.floor(x / y), precision);
  1398. };
  1399. var mod = floatMod(value - options.baseValue, options.step);
  1400. return (mod == 0.0 || mod == options.step);
  1401. }
  1402. };
  1403. }(window.jQuery));
  1404. ;(function($) {
  1405. $.fn.bootstrapValidator.validators.stringLength = {
  1406. html5Attributes: ['message', 'min', 'max'],
  1407. /**
  1408. * Check if the length of element value is less or more than given number
  1409. *
  1410. * @param {BootstrapValidator} validator The validator plugin instance
  1411. * @param {jQuery} $field Field element
  1412. * @param {Object} options Consists of following keys:
  1413. * - min
  1414. * - max
  1415. * At least one of two keys is required
  1416. * @returns {Boolean}
  1417. */
  1418. validate: function(validator, $field, options) {
  1419. var value = $field.val();
  1420. if (value == '') {
  1421. return true;
  1422. }
  1423. var length = $.trim(value).length;
  1424. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  1425. return false;
  1426. }
  1427. return true;
  1428. }
  1429. };
  1430. }(window.jQuery));
  1431. ;(function($) {
  1432. $.fn.bootstrapValidator.validators.uri = {
  1433. enableByHtml5: function($field) {
  1434. return ('url' == $field.attr('type'));
  1435. },
  1436. /**
  1437. * Return true if the input value is a valid URL
  1438. *
  1439. * @param {BootstrapValidator} validator The validator plugin instance
  1440. * @param {jQuery} $field Field element
  1441. * @param {Object} options
  1442. * @returns {Boolean}
  1443. */
  1444. validate: function(validator, $field, options) {
  1445. var value = $field.val();
  1446. if (value == '') {
  1447. return true;
  1448. }
  1449. // Credit to https://gist.github.com/dperini/729294
  1450. //
  1451. // Regular Expression for URL validation
  1452. //
  1453. // Author: Diego Perini
  1454. // Updated: 2010/12/05
  1455. //
  1456. // the regular expression composed & commented
  1457. // could be easily tweaked for RFC compliance,
  1458. // it was expressly modified to fit & satisfy
  1459. // these test for an URL shortener:
  1460. //
  1461. // http://mathiasbynens.be/demo/url-regex
  1462. //
  1463. // Notes on possible differences from a standard/generic validation:
  1464. //
  1465. // - utf-8 char class take in consideration the full Unicode range
  1466. // - TLDs have been made mandatory so single names like "localhost" fails
  1467. // - protocols have been restricted to ftp, http and https only as requested
  1468. //
  1469. // Changes:
  1470. //
  1471. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  1472. // first and last IP address of each class is considered invalid
  1473. // (since they are broadcast/network addresses)
  1474. //
  1475. // - Added exclusion of private, reserved and/or local networks ranges
  1476. //
  1477. // Compressed one-line versions:
  1478. //
  1479. // Javascript version
  1480. //
  1481. // /^(?:(?: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
  1482. //
  1483. // PHP version
  1484. //
  1485. // _^(?:(?: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
  1486. var urlExp = new RegExp(
  1487. "^" +
  1488. // protocol identifier
  1489. "(?:(?:https?|ftp)://)" +
  1490. // user:pass authentication
  1491. "(?:\\S+(?::\\S*)?@)?" +
  1492. "(?:" +
  1493. // IP address exclusion
  1494. // private & local networks
  1495. "(?!10(?:\\.\\d{1,3}){3})" +
  1496. "(?!127(?:\\.\\d{1,3}){3})" +
  1497. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1498. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1499. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1500. // IP address dotted notation octets
  1501. // excludes loopback network 0.0.0.0
  1502. // excludes reserved space >= 224.0.0.0
  1503. // excludes network & broacast addresses
  1504. // (first & last IP address of each class)
  1505. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1506. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1507. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1508. "|" +
  1509. // host name
  1510. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1511. // domain name
  1512. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1513. // TLD identifier
  1514. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1515. ")" +
  1516. // port number
  1517. "(?::\\d{2,5})?" +
  1518. // resource path
  1519. "(?:/[^\\s]*)?" +
  1520. "$", "i"
  1521. );
  1522. return urlExp.test(value);
  1523. }
  1524. };
  1525. }(window.jQuery));
  1526. ;(function($) {
  1527. $.fn.bootstrapValidator.validators.zipCode = {
  1528. html5Attributes: ['message', 'country'],
  1529. /**
  1530. * Return true if and only if the input value is a valid country zip code
  1531. *
  1532. * @param {BootstrapValidator} validator The validator plugin instance
  1533. * @param {jQuery} $field Field element
  1534. * @param {Object} options Consist of key:
  1535. * - message: The invalid message
  1536. * - country: The ISO 3166 country code
  1537. *
  1538. * Currently it supports the following countries:
  1539. * - US (United State)
  1540. * - DK (Denmark)
  1541. * - SE (Sweden)
  1542. * @returns {Boolean}
  1543. */
  1544. validate: function(validator, $field, options) {
  1545. var value = $field.val();
  1546. if (value == '' || !options.country) {
  1547. return true;
  1548. }
  1549. options.country = options.country || 'US';
  1550. switch (options.country.toUpperCase()) {
  1551. case 'DK':
  1552. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1553. case 'SE':
  1554. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1555. case 'US':
  1556. default:
  1557. return /^\d{5}([\-]\d{4})?$/.test(value);
  1558. }
  1559. }
  1560. };
  1561. }(window.jQuery));