| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777 |
- /**
- * BootstrapValidator (http://bootstrapvalidator.com)
- * The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3
- *
- * @author http://twitter.com/nghuuphuoc
- * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
- * @license MIT
- */
- (function($) {
- var BootstrapValidator = function(form, options) {
- this.$form = $(form);
- this.options = $.extend({}, $.fn.bootstrapValidator.DEFAULT_OPTIONS, options);
- this.$invalidFields = $([]); // Array of invalid fields
- this.$submitButton = null; // The submit button which is clicked to submit form
- // Validating status
- this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
- this.STATUS_VALIDATING = 'VALIDATING';
- this.STATUS_INVALID = 'INVALID';
- this.STATUS_VALID = 'VALID';
- // Determine the event that is fired when user change the field value
- // Most modern browsers supports input event except IE 7, 8.
- // IE 9 supports input event but the event is still not fired if I press the backspace key.
- // Get IE version
- // https://gist.github.com/padolsey/527683/#comment-7595
- var ieVersion = (function() {
- var v = 3, div = document.createElement('div'), a = div.all || [];
- while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]) {}
- return v > 4 ? v : !v;
- }());
- var el = document.createElement('div');
- this._changeEvent = (ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
- // The flag to indicate that the form is ready to submit when a remote/callback validator returns
- this._submitIfValid = null;
- // Field elements
- this._cacheFields = {};
- this._init();
- };
- BootstrapValidator.prototype = {
- constructor: BootstrapValidator,
- /**
- * Init form
- */
- _init: function() {
- var that = this,
- options = {
- excluded: this.$form.attr('data-bv-excluded'),
- trigger: this.$form.attr('data-bv-trigger'),
- message: this.$form.attr('data-bv-message'),
- container: this.$form.attr('data-bv-container'),
- group: this.$form.attr('data-bv-group'),
- submitButtons: this.$form.attr('data-bv-submitbuttons'),
- threshold: this.$form.attr('data-bv-threshold'),
- live: this.$form.attr('data-bv-live'),
- onSuccess: this.$form.attr('data-bv-onsuccess'),
- onError: this.$form.attr('data-bv-onerror'),
- fields: {},
- feedbackIcons: {
- valid: this.$form.attr('data-bv-feedbackicons-valid'),
- invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
- validating: this.$form.attr('data-bv-feedbackicons-validating')
- }
- };
- this.$form
- // Disable client side validation in HTML 5
- .attr('novalidate', 'novalidate')
- .addClass(this.options.elementClass)
- // Disable the default submission first
- .on('submit.bv', function(e) {
- e.preventDefault();
- that.validate();
- })
- .on('click.bv', this.options.submitButtons, function() {
- that.$submitButton = $(this);
- // The user just click the submit button
- that._submitIfValid = true;
- })
- // Find all fields which have either "name" or "data-bv-field" attribute
- .find('[name], [data-bv-field]')
- .each(function() {
- var $field = $(this),
- field = $field.attr('name') || $field.attr('data-bv-field'),
- opts = that._parseOptions($field);
- if (opts) {
- $field.attr('data-bv-field', field);
- options.fields[field] = $.extend({}, opts, options.fields[field]);
- }
- });
- this.options = $.extend(true, this.options, options);
- for (var field in this.options.fields) {
- this._initField(field);
- }
- this.$form.trigger($.Event('init.form.bv'), {
- options: this.options
- });
- // Prepare the events
- if (this.options.onSuccess) {
- this.$form.on('success.form.bv', function(e) {
- $.fn.bootstrapValidator.helpers.call(that.options.onSuccess, [e]);
- });
- }
- if (this.options.onError) {
- this.$form.on('error.form.bv', function(e) {
- $.fn.bootstrapValidator.helpers.call(that.options.onError, [e]);
- });
- }
- },
- /**
- * Parse the validator options from HTML attributes
- *
- * @param {jQuery} $field The field element
- * @returns {Object}
- */
- _parseOptions: function($field) {
- var field = $field.attr('name') || $field.attr('data-bv-field'),
- validators = {},
- validator,
- v, // Validator name
- enabled,
- optionName,
- optionValue,
- html5AttrName,
- html5AttrMap;
- for (v in $.fn.bootstrapValidator.validators) {
- validator = $.fn.bootstrapValidator.validators[v];
- enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
- html5AttrMap = ('function' === typeof validator.enableByHtml5) ? validator.enableByHtml5($field) : null;
- if ((html5AttrMap && enabled !== 'false')
- || (html5AttrMap !== true && ('' === enabled || 'true' === enabled)))
- {
- // Try to parse the options via attributes
- validator.html5Attributes = validator.html5Attributes || { message: 'message' };
- validators[v] = $.extend({}, html5AttrMap === true ? {} : html5AttrMap, validators[v]);
- for (html5AttrName in validator.html5Attributes) {
- optionName = validator.html5Attributes[html5AttrName];
- optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + html5AttrName);
- if (optionValue) {
- if ('true' === optionValue) {
- optionValue = true;
- } else if ('false' === optionValue) {
- optionValue = false;
- }
- validators[v][optionName] = optionValue;
- }
- }
- }
- }
- var opts = {
- excluded: $field.attr('data-bv-excluded'),
- feedbackIcons: $field.attr('data-bv-feedbackicons'),
- trigger: $field.attr('data-bv-trigger'),
- message: $field.attr('data-bv-message'),
- container: $field.attr('data-bv-container'),
- group: $field.attr('data-bv-group'),
- selector: $field.attr('data-bv-selector'),
- threshold: $field.attr('data-bv-threshold'),
- onSuccess: $field.attr('data-bv-onsuccess'),
- onError: $field.attr('data-bv-onerror'),
- validators: validators
- },
- emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
- emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
- if (!emptyValidators || (!emptyOptions && this.options.fields && this.options.fields[field])) {
- opts.validators = validators;
- return opts;
- } else {
- return null;
- }
- },
- /**
- * Init field
- *
- * @param {String|jQuery} field The field name or field element
- */
- _initField: function(field) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- fields.attr('data-bv-field', field);
- break;
- default:
- break;
- }
- if (this.options.fields[field] === null || this.options.fields[field].validators === null) {
- return;
- }
- // We don't need to validate non-existing fields
- if (fields.length === 0) {
- delete this.options.fields[field];
- return;
- }
- var validatorName;
- for (validatorName in this.options.fields[field].validators) {
- if (!$.fn.bootstrapValidator.validators[validatorName]) {
- delete this.options.fields[field].validators[validatorName];
- }
- }
- if (this.options.fields[field].enabled === null) {
- this.options.fields[field].enabled = true;
- }
- var that = this,
- total = fields.length,
- type = fields.attr('type'),
- updateAll = (total === 1) || ('radio' === type) || ('checkbox' === type),
- event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === fields.eq(0).get(0).tagName) ? 'change' : this._changeEvent,
- trigger = (this.options.fields[field].trigger || this.options.trigger || event).split(' '),
- events = $.map(trigger, function(item) {
- return item + '.update.bv';
- }).join(' ');
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i),
- group = this.options.fields[field].group || this.options.group,
- $parent = $field.parents(group),
- // Allow user to indicate where the error messages are shown
- container = this.options.fields[field].container || this.options.container,
- $message = (container && container !== 'tooltip' && container !== 'popover') ? $(container) : this._getMessageContainer($field, group);
- if (container && container !== 'tooltip' && container !== 'popover') {
- $message.addClass('has-error');
- }
- // Remove all error messages and feedback icons
- $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove();
- $parent.find('i[data-bv-icon-for="' + field + '"]').remove();
- // Whenever the user change the field value, mark it as not validated yet
- $field.off(events).on(events, function() {
- that.updateStatus($(this), that.STATUS_NOT_VALIDATED);
- });
- // Create help block elements for showing the error messages
- $field.data('bv.messages', $message);
- for (validatorName in this.options.fields[field].validators) {
- $field.data('bv.result.' + validatorName, this.STATUS_NOT_VALIDATED);
- if (!updateAll || i === total - 1) {
- $('<small/>')
- .css('display', 'none')
- .addClass('help-block')
- .attr('data-bv-validator', validatorName)
- .attr('data-bv-for', field)
- .attr('data-bv-result', this.STATUS_NOT_VALIDATED)
- .html(this._getMessage(field, validatorName))
- .appendTo($message);
- }
- }
- // Prepare the feedback icons
- // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
- if (this.options.fields[field].feedbackIcons !== false && this.options.fields[field].feedbackIcons !== 'false'
- && this.options.feedbackIcons
- && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid
- && (!updateAll || i === total - 1))
- {
- $parent.removeClass('has-success').removeClass('has-error').addClass('has-feedback');
- var $icon = $('<i/>')
- .css('display', 'none')
- .addClass('form-control-feedback')
- .attr('data-bv-icon-for', field)
- // Place it after the label containing the checkbox/radio
- // so when clicking the icon, it doesn't effect to the checkbox/radio element
- .insertAfter(('checkbox' === type || 'radio' === type) ? $field.parent() : $field);
- // The feedback icon does not render correctly if there is no label
- // https://github.com/twbs/bootstrap/issues/12873
- if ($parent.find('label').length === 0) {
- $icon.css('top', 0);
- }
- // Fix feedback icons in input-group
- if ($parent.find('.input-group').length !== 0) {
- $icon.css({
- 'top': 0,
- 'z-index': 100
- }).insertAfter($parent.find('.input-group').eq(0));
- }
- }
- }
- // Prepare the events
- if (this.options.fields[field].onSuccess) {
- fields.on('success.field.bv', function(e, data) {
- $.fn.bootstrapValidator.helpers.call(that.options.fields[field].onSuccess, [e, data]);
- });
- }
- if (this.options.fields[field].onError) {
- fields.on('error.field.bv', function(e, data) {
- $.fn.bootstrapValidator.helpers.call(that.options.fields[field].onError, [e, data]);
- });
- }
- // Set live mode
- events = $.map(trigger, function(item) {
- return item + '.live.bv';
- }).join(' ');
- switch (this.options.live) {
- case 'submitted':
- break;
- case 'disabled':
- fields.off(events);
- break;
- case 'enabled':
- /* falls through */
- default:
- fields.off(events).on(events, function() {
- if (that._exceedThreshold($(this))) {
- that.validateField($(this));
- }
- });
- break;
- }
- this.$form.trigger($.Event('init.field.bv'), {
- field: field,
- element: fields
- });
- },
- /**
- * Get the error message for given field and validator
- *
- * @param {String} field The field name
- * @param {String} validatorName The validator name
- * @returns {String}
- */
- _getMessage: function(field, validatorName) {
- if (!this.options.fields[field] || !$.fn.bootstrapValidator.validators[validatorName]
- || !this.options.fields[field].validators || !this.options.fields[field].validators[validatorName])
- {
- return '';
- }
- var options = this.options.fields[field].validators[validatorName];
- switch (true) {
- case (!!options.message):
- return options.message;
- case (!!this.options.fields[field].message):
- return this.options.fields[field].message;
- case (!!$.fn.bootstrapValidator.i18n[validatorName]):
- return $.fn.bootstrapValidator.i18n[validatorName]['default'];
- default:
- return this.options.message;
- }
- },
- /**
- * Get the element to place the error messages
- *
- * @param {jQuery} $field The field element
- * @param {String} group
- * @returns {jQuery}
- */
- _getMessageContainer: function($field, group) {
- var $parent = $field.parent();
- if ($parent.is(group)) {
- return $parent;
- }
- var cssClasses = $parent.attr('class');
- if (!cssClasses) {
- return this._getMessageContainer($parent, group);
- }
- cssClasses = cssClasses.split(' ');
- var n = cssClasses.length;
- for (var i = 0; i < n; i++) {
- if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
- return $parent;
- }
- }
- return this._getMessageContainer($parent, group);
- },
- /**
- * Called when all validations are completed
- */
- _submit: function() {
- var isValid = this.isValid(),
- eventType = isValid ? 'success.form.bv' : 'error.form.bv',
- e = $.Event(eventType);
- this.$form.trigger(e);
- // Call default handler
- // Check if whether the submit button is clicked
- if (this.$submitButton) {
- isValid ? this._onSuccess(e) : this._onError(e);
- }
- },
- /**
- * Check if the field is excluded.
- * Returning true means that the field will not be validated
- *
- * @param {jQuery} $field The field element
- * @returns {Boolean}
- */
- _isExcluded: function($field) {
- var excludedAttr = $field.attr('data-bv-excluded'),
- // I still need to check the 'name' attribute while initializing the field
- field = $field.attr('data-bv-field') || $field.attr('name');
- switch (true) {
- case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'true' || this.options.fields[field].excluded === true)):
- case (excludedAttr === 'true'):
- case (excludedAttr === ''):
- return true;
- case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'false' || this.options.fields[field].excluded === false)):
- case (excludedAttr === 'false'):
- return false;
- default:
- if (this.options.excluded) {
- // Convert to array first
- if ('string' === typeof this.options.excluded) {
- this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
- // Trim the spaces
- return $.trim(item);
- });
- }
- var length = this.options.excluded.length;
- for (var i = 0; i < length; i++) {
- if (('string' === typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
- || ('function' === typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) === true))
- {
- return true;
- }
- }
- }
- return false;
- }
- },
- /**
- * Check if the number of characters of field value exceed the threshold or not
- *
- * @param {jQuery} $field The field element
- * @returns {Boolean}
- */
- _exceedThreshold: function($field) {
- var field = $field.attr('data-bv-field'),
- threshold = this.options.fields[field].threshold || this.options.threshold;
- if (!threshold) {
- return true;
- }
- var cannotType = $.inArray($field.attr('type'), ['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit']) !== -1;
- return (cannotType || $field.val().length >= threshold);
- },
-
- // ---
- // Events
- // ---
- /**
- * The default handler of error.form.bv event.
- * It will be called when there is a invalid field
- *
- * @param {jQuery.Event} e The jQuery event object
- */
- _onError: function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
- if ('submitted' === this.options.live) {
- // Enable live mode
- this.options.live = 'enabled';
- var that = this;
- for (var field in this.options.fields) {
- (function(f) {
- var fields = that.getFieldElements(f);
- if (fields.length) {
- var type = $(fields[0]).attr('type'),
- event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === $(fields[0]).get(0).tagName) ? 'change' : that._changeEvent,
- trigger = that.options.fields[field].trigger || that.options.trigger || event,
- events = $.map(trigger.split(' '), function(item) {
- return item + '.live.bv';
- }).join(' ');
- fields.off(events).on(events, function() {
- if (that._exceedThreshold($(this))) {
- that.validateField($(this));
- }
- });
- }
- })(field);
- }
- }
- var $invalidField = this.$invalidFields.eq(0);
- if ($invalidField) {
- // Activate the tab containing the invalid field if exists
- var $tabPane = $invalidField.parents('.tab-pane'), tabId;
- if ($tabPane && (tabId = $tabPane.attr('id'))) {
- $('a[href="#' + tabId + '"][data-toggle="tab"]').tab('show');
- }
- // Focus to the first invalid field
- $invalidField.focus();
- }
- },
- /**
- * The default handler of success.form.bv event.
- * It will be called when all the fields are valid
- *
- * @param {jQuery.Event} e The jQuery event object
- */
- _onSuccess: function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
- // Call the custom submission if enabled
- if (this.options.submitHandler && 'function' === typeof this.options.submitHandler) {
- // If you want to submit the form inside your submit handler, please call defaultSubmit() method
- this.options.submitHandler.call(this, this, this.$form);
- } else {
- this.disableSubmitButtons(true).defaultSubmit();
- }
- },
- /**
- * Called after validating a field element
- *
- * @param {jQuery} $field The field element
- * @param {String} [validatorName] The validator name
- */
- _onFieldValidated: function($field, validatorName) {
- var field = $field.attr('data-bv-field'),
- validators = this.options.fields[field].validators,
- counter = {},
- numValidators = 0;
- // Trigger an event after given validator completes
- if (validatorName) {
- var data = {
- field: field,
- element: $field,
- validator: validatorName
- };
- switch ($field.data('bv.result.' + validatorName)) {
- case this.STATUS_INVALID:
- this.$form.trigger($.Event('error.validator.bv'), data);
- break;
- case this.STATUS_VALID:
- this.$form.trigger($.Event('success.validator.bv'), data);
- break;
- default:
- break;
- }
- }
- counter[this.STATUS_NOT_VALIDATED] = 0;
- counter[this.STATUS_VALIDATING] = 0;
- counter[this.STATUS_INVALID] = 0;
- counter[this.STATUS_VALID] = 0;
- for (var v in validators) {
- if (validators[v].enabled === false) {
- continue;
- }
- numValidators++;
- var result = $field.data('bv.result.' + v);
- if (result) {
- counter[result]++;
- }
- }
- if (counter[this.STATUS_VALID] === numValidators) {
- // Remove from the list of invalid fields
- this.$invalidFields = this.$invalidFields.not($field);
- this.$form.trigger($.Event('success.field.bv'), {
- field: field,
- element: $field
- });
- $field.trigger($.Event('success.field.bv'), {
- field: field,
- element: $field,
- validator: this
- });
- }
- // If all validators are completed and there is at least one validator which doesn't pass
- else if (counter[this.STATUS_NOT_VALIDATED] === 0 && counter[this.STATUS_VALIDATING] === 0 && counter[this.STATUS_INVALID] > 0) {
- // Add to the list of invalid fields
- this.$invalidFields = this.$invalidFields.add($field);
- this.$form.trigger($.Event('error.field.bv'), {
- field: field,
- element: $field
- });
- $field.trigger($.Event('error.field.bv'), {
- field: field,
- element: $field,
- validator: this
- });
- }
- },
- // ---
- // Public methods
- // ---
- /**
- * Retrieve the field elements by given name
- *
- * @param {String} field The field name
- * @returns {null|jQuery[]}
- */
- getFieldElements: function(field) {
- if (!this._cacheFields[field]) {
- this._cacheFields[field] = (this.options.fields[field] && this.options.fields[field].selector)
- ? $(this.options.fields[field].selector)
- : this.$form.find('[name="' + field + '"]');
- }
- return this._cacheFields[field];
- },
- /**
- * Disable/enable submit buttons
- *
- * @param {Boolean} disabled Can be true or false
- * @returns {BootstrapValidator}
- */
- disableSubmitButtons: function(disabled) {
- if (!disabled) {
- this.$form.find(this.options.submitButtons).removeAttr('disabled');
- } else if (this.options.live !== 'disabled') {
- // Don't disable if the live validating mode is disabled
- this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
- }
- return this;
- },
- /**
- * Validate the form
- *
- * @returns {BootstrapValidator}
- */
- validate: function() {
- if (!this.options.fields) {
- return this;
- }
- this.disableSubmitButtons(true);
- for (var field in this.options.fields) {
- this.validateField(field);
- }
- this._submit();
- return this;
- },
- /**
- * Validate given field
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {BootstrapValidator}
- */
- validateField: function(field) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (this.options.fields[field] && this.options.fields[field].enabled === false) {
- return this;
- }
- var that = this,
- type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
- updateAll = ('radio' === type || 'checkbox' === type),
- validators = this.options.fields[field].validators,
- validatorName,
- validateResult;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- for (validatorName in validators) {
- if ($field.data('bv.dfs.' + validatorName)) {
- $field.data('bv.dfs.' + validatorName).reject();
- }
- // Don't validate field if it is already done
- var result = $field.data('bv.result.' + validatorName);
- if (result === this.STATUS_VALID || result === this.STATUS_INVALID || validators[validatorName].enabled === false) {
- this._onFieldValidated($field, validatorName);
- continue;
- }
- $field.data('bv.result.' + validatorName, this.STATUS_VALIDATING);
- validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
- // validateResult can be a $.Deferred object ...
- if ('object' === typeof validateResult && validateResult.resolve) {
- this.updateStatus(updateAll ? field : $field, this.STATUS_VALIDATING, validatorName);
- $field.data('bv.dfs.' + validatorName, validateResult);
- validateResult.done(function($f, v, isValid, message) {
- // v is validator name
- $f.removeData('bv.dfs.' + v);
- if (message) {
- that.updateMessage($f, v, message);
- }
- that.updateStatus(updateAll ? $f.attr('data-bv-field') : $f, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
- if (isValid && that._submitIfValid === true) {
- // If a remote validator returns true and the form is ready to submit, then do it
- that._submit();
- }
- });
- }
- // ... or object { valid: true/false, message: 'dynamic message' }
- else if ('object' === typeof validateResult && validateResult.valid !== undefined && validateResult.message !== undefined) {
- this.updateMessage(updateAll ? field : $field, validatorName, validateResult.message);
- this.updateStatus(updateAll ? field : $field, validateResult.valid ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
- }
- // ... or a boolean value
- else if ('boolean' === typeof validateResult) {
- this.updateStatus(updateAll ? field : $field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
- }
- }
- }
- return this;
- },
- /**
- * Update the error message
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validator The validator name
- * @param {String} message The message
- * @returns {BootstrapValidator}
- */
- updateMessage: function(field, validator, message) {
- var $fields = $([]);
- switch (typeof field) {
- case 'object':
- $fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- $fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- $fields.each(function() {
- $(this).data('bv.messages').find('.help-block[data-bv-validator="' + validator + '"][data-bv-for="' + field + '"]').html(message);
- });
- },
-
- /**
- * Update all validating results of field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
- * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
- * @returns {BootstrapValidator}
- */
- updateStatus: function(field, status, validatorName) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (status === this.STATUS_NOT_VALIDATED) {
- // Reset the flag
- this._submitIfValid = false;
- }
- var that = this,
- type = fields.attr('type'),
- group = this.options.fields[field].group || this.options.group,
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- var $parent = $field.parents(group),
- $message = $field.data('bv.messages'),
- $allErrors = $message.find('.help-block[data-bv-validator][data-bv-for="' + field + '"]'),
- $errors = validatorName ? $allErrors.filter('[data-bv-validator="' + validatorName + '"]') : $allErrors,
- $icon = $parent.find('.form-control-feedback[data-bv-icon-for="' + field + '"]'),
- container = this.options.fields[field].container || this.options.container,
- isValidField = null;
- // Update status
- if (validatorName) {
- $field.data('bv.result.' + validatorName, status);
- } else {
- for (var v in this.options.fields[field].validators) {
- $field.data('bv.result.' + v, status);
- }
- }
- // Show/hide error elements and feedback icons
- $errors.attr('data-bv-result', status);
- // Determine the tab containing the element
- var $tabPane = $field.parents('.tab-pane'),
- tabId, $tab;
- if ($tabPane && (tabId = $tabPane.attr('id'))) {
- $tab = $('a[href="#' + tabId + '"][data-toggle="tab"]').parent();
- }
- switch (status) {
- case this.STATUS_VALIDATING:
- isValidField = null;
- this.disableSubmitButtons(true);
- $parent.removeClass('has-success').removeClass('has-error');
- if ($icon) {
- $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
- }
- if ($tab) {
- $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
- }
- break;
- case this.STATUS_INVALID:
- isValidField = false;
- this.disableSubmitButtons(true);
- $parent.removeClass('has-success').addClass('has-error');
- if ($icon) {
- $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
- }
- if ($tab) {
- $tab.removeClass('bv-tab-success').addClass('bv-tab-error');
- }
- break;
- case this.STATUS_VALID:
- // If the field is valid (passes all validators)
- isValidField = ($allErrors.filter('[data-bv-result="' + this.STATUS_NOT_VALIDATED +'"]').length === 0)
- ? ($allErrors.filter('[data-bv-result="' + this.STATUS_VALID +'"]').length === $allErrors.length) // All validators are completed
- : null; // There are some validators that have not done
- if (isValidField !== null) {
- this.disableSubmitButtons(this.$submitButton ? !this.isValid() : !isValidField);
- if ($icon) {
- $icon
- .removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid)
- .addClass(isValidField ? this.options.feedbackIcons.valid : this.options.feedbackIcons.invalid)
- .show();
- }
- }
- $parent.removeClass('has-error has-success').addClass(this.isValidContainer($parent) ? 'has-success' : 'has-error');
- if ($tab) {
- $tab.removeClass('bv-tab-success').removeClass('bv-tab-error').addClass(this.isValidContainer($tabPane) ? 'bv-tab-success' : 'bv-tab-error');
- }
- break;
- case this.STATUS_NOT_VALIDATED:
- /* falls through */
- default:
- isValidField = null;
- this.disableSubmitButtons(false);
- $parent.removeClass('has-success').removeClass('has-error');
- if ($icon) {
- $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
- }
- if ($tab) {
- $tab.removeClass('bv-tab-success').removeClass('bv-tab-error');
- }
- break;
- }
- switch (true) {
- // Only show the first error message if it is placed inside a tooltip ...
- case ($icon && 'tooltip' === container):
- (isValidField === false)
- ? $icon.css('cursor', 'pointer').tooltip('destroy').tooltip({
- html: true,
- placement: 'top',
- title: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html()
- })
- : $icon.css('cursor', '').tooltip('destroy');
- break;
- // ... or popover
- case ($icon && 'popover' === container):
- (isValidField === false)
- ? $icon.css('cursor', 'pointer').popover('destroy').popover({
- content: $allErrors.filter('[data-bv-result="' + that.STATUS_INVALID + '"]').eq(0).html(),
- html: true,
- placement: 'top',
- trigger: 'hover click'
- })
- : $icon.css('cursor', '').popover('destroy');
- break;
- default:
- (status === this.STATUS_INVALID) ? $errors.show() : $errors.hide();
- break;
- }
- // Trigger an event
- this.$form.trigger($.Event('status.field.bv'), {
- field: field,
- element: $field,
- status: status
- });
- this._onFieldValidated($field, validatorName);
- }
- return this;
- },
- /**
- * Check the form validity
- *
- * @returns {Boolean}
- */
- isValid: function() {
- for (var field in this.options.fields) {
- if (!this.isValidField(field)) {
- return false;
- }
- }
- return true;
- },
- /**
- * Check if the field is valid or not
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {Boolean}
- */
- isValidField: function(field) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (fields.length === 0 || this.options.fields[field] === null || this.options.fields[field].enabled === false) {
- return true;
- }
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
- $field, validatorName, status;
- for (var i = 0; i < total; i++) {
- $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- for (validatorName in this.options.fields[field].validators) {
- if (this.options.fields[field].validators[validatorName].enabled === false) {
- continue;
- }
- status = $field.data('bv.result.' + validatorName);
- if (status !== this.STATUS_VALID) {
- return false;
- }
- }
- }
- return true;
- },
- /**
- * Check if all fields inside a given container are valid.
- * It's useful when working with a wizard-like such as tab, collapse
- *
- * @param {jQuery} $container The container element
- * @returns {Boolean}
- */
- isValidContainer: function($container) {
- var that = this, map = {};
- $container.find('[data-bv-field]').each(function() {
- var $field = $(this),
- field = $field.attr('data-bv-field');
- if (!that._isExcluded($field) && !map[field]) {
- map[field] = $field;
- }
- });
- for (var field in map) {
- var $f = map[field];
- if ($f.data('bv.messages')
- .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]')
- .filter(function() {
- var v = $(this).attr('data-bv-validator'),
- f = $(this).attr('data-bv-for');
- return (that.options.fields[f].validators[v].enabled !== false
- && $f.data('bv.result.' + v) && $f.data('bv.result.' + v) !== that.STATUS_VALID);
- })
- .length !== 0)
- {
- // The field is not valid
- return false;
- }
- }
- return true;
- },
- /**
- * Submit the form using default submission.
- * It also does not perform any validations when submitting the form
- *
- * It might be used when you want to submit the form right inside the submitHandler()
- */
- defaultSubmit: function() {
- if (this.$submitButton) {
- // Create hidden input to send the submit buttons
- $('<input/>')
- .attr('type', 'hidden')
- .attr('data-bv-submit-hidden', '')
- .attr('name', this.$submitButton.attr('name'))
- .val(this.$submitButton.val())
- .appendTo(this.$form);
- }
- // Submit form
- this.$form.off('submit.bv').submit();
- },
- // ---
- // Useful APIs which aren't used internally
- // ---
- /**
- * Get the list of invalid fields
- *
- * @returns {jQuery[]}
- */
- getInvalidFields: function() {
- return this.$invalidFields;
- },
- /**
- * Returns the clicked submit button
- *
- * @returns {jQuery}
- */
- getSubmitButton: function() {
- return this.$submitButton;
- },
- /**
- * Get the error messages
- *
- * @param {String|jQuery} [field] The field name or field element
- * If the field is not defined, the method returns all error messages of all fields
- * @param {String} [validator] The name of validator
- * If the validator is not defined, the method returns error messages of all validators
- * @returns {String[]}
- */
- getMessages: function(field, validator) {
- var that = this,
- messages = [],
- $fields = $([]);
- switch (true) {
- case (field && 'object' === typeof field):
- $fields = field;
- break;
- case (field && 'string' === typeof field):
- var f = this.getFieldElements(field);
- if (f.length > 0) {
- var type = f.attr('type');
- $fields = ('radio' === type || 'checkbox' === type) ? f.eq(0) : f;
- }
- break;
- default:
- $fields = this.$invalidFields;
- break;
- }
- var filter = validator ? '[data-bv-validator="' + validator + '"]' : '';
- $fields.each(function() {
- messages = messages.concat(
- $(this)
- .data('bv.messages')
- .find('.help-block[data-bv-for="' + $(this).attr('data-bv-field') + '"][data-bv-result="' + that.STATUS_INVALID + '"]' + filter)
- .map(function() {
- var v = $(this).attr('data-bv-validator'),
- f = $(this).attr('data-bv-for');
- return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
- })
- .get()
- );
- });
- return messages;
- },
- /**
- * Update the option of a specific validator
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validator The validator name
- * @param {String} option The option name
- * @param {String} value The value to set
- * @returns {BootstrapValidator}
- */
- updateOption: function(field, validator, option, value) {
- if ('object' === typeof field) {
- field = field.attr('data-bv-field');
- }
- if (this.options.fields[field] && this.options.fields[field].validators[validator]) {
- this.options.fields[field].validators[validator][option] = value;
- this.updateStatus(field, this.STATUS_NOT_VALIDATED, validator);
- }
- return this;
- },
- /**
- * Add a new field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {Object} [options] The validator rules
- * @returns {BootstrapValidator}
- */
- addField: function(field, options) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field') || field.attr('name');
- break;
- case 'string':
- delete this._cacheFields[field];
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- fields.attr('data-bv-field', field);
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- // Try to parse the options from HTML attributes
- var opts = this._parseOptions($field);
- opts = (opts === null) ? options : $.extend(true, options, opts);
- this.options.fields[field] = $.extend(true, this.options.fields[field], opts);
- // Update the cache
- this._cacheFields[field] = this._cacheFields[field] ? this._cacheFields[field].add($field) : $field;
- // Init the element
- this._initField(('checkbox' === type || 'radio' === type) ? field : $field);
- }
- this.disableSubmitButtons(false);
- // Trigger an event
- this.$form.trigger($.Event('added.field.bv'), {
- field: field,
- element: fields,
- options: this.options.fields[field]
- });
- return this;
- },
- /**
- * Remove a given field
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {BootstrapValidator}
- */
- removeField: function(field) {
- var fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-bv-field') || field.attr('name');
- fields.attr('data-bv-field', field);
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (fields.length === 0) {
- return this;
- }
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- // Remove from the list of invalid fields
- this.$invalidFields = this.$invalidFields.not($field);
- // Update the cache
- this._cacheFields[field] = this._cacheFields[field].not($field);
- }
- if (!this._cacheFields[field] || this._cacheFields[field].length === 0) {
- delete this.options.fields[field];
- }
- if ('checkbox' === type || 'radio' === type) {
- this._initField(field);
- }
- this.disableSubmitButtons(false);
- // Trigger an event
- this.$form.trigger($.Event('removed.field.bv'), {
- field: field,
- element: fields
- });
- return this;
- },
- /**
- * Reset given field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
- * @returns {BootstrapValidator}
- */
- resetField: function(field, resetValue) {
- var $fields = $([]);
- switch (typeof field) {
- case 'object':
- $fields = field;
- field = field.attr('data-bv-field');
- break;
- case 'string':
- $fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- var total = $fields.length;
- if (this.options.fields[field]) {
- for (var i = 0; i < total; i++) {
- for (var validator in this.options.fields[field].validators) {
- $fields.eq(i).removeData('bv.dfs.' + validator);
- }
- }
- }
- // Mark field as not validated yet
- this.updateStatus(field, this.STATUS_NOT_VALIDATED);
- if (resetValue) {
- var type = $fields.attr('type');
- ('radio' === type || 'checkbox' === type) ? $fields.removeAttr('checked').removeAttr('selected') : $fields.val('');
- }
- return this;
- },
- /**
- * Reset the form
- *
- * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
- * @returns {BootstrapValidator}
- */
- resetForm: function(resetValue) {
- for (var field in this.options.fields) {
- this.resetField(field, resetValue);
- }
- this.$invalidFields = $([]);
- this.$submitButton = null;
- // Enable submit buttons
- this.disableSubmitButtons(false);
- return this;
- },
- /**
- * Revalidate given field
- * It's used when you need to revalidate the field which its value is updated by other plugin
- *
- * @param {String|jQuery} field The field name of field element
- * @returns {BootstrapValidator}
- */
- revalidateField: function(field) {
- this.updateStatus(field, this.STATUS_NOT_VALIDATED)
- .validateField(field);
- return this;
- },
- /**
- * Enable/Disable all validators to given field
- *
- * @param {String} field The field name
- * @param {Boolean} enabled Enable/Disable field validators
- * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
- * @returns {BootstrapValidator}
- */
- enableFieldValidators: function(field, enabled, validatorName) {
- var validators = this.options.fields[field].validators;
- // Enable/disable particular validator
- if (validatorName
- && validators
- && validators[validatorName] && validators[validatorName].enabled !== enabled)
- {
- this.options.fields[field].validators[validatorName].enabled = enabled;
- this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
- }
- // Enable/disable all validators
- else if (!validatorName && this.options.fields[field].enabled !== enabled) {
- this.options.fields[field].enabled = enabled;
- for (var v in validators) {
- this.enableFieldValidators(field, enabled, v);
- }
- }
- return this;
- },
- /**
- * Some other validators have option which its value is dynamic.
- * For example, the zipCode validator which country is set by a select element.
- *
- * @param {String|Function} option The option which can be determined by:
- * - a string
- * - name of field which defines the value
- * - name of function which returns the value
- * - a function returns the value
- *
- * The callback function has the format of
- * callback: function(value, validator, $field) {
- * // value is the value of field
- * // validator is the BootstrapValidator instance
- * // $field is the field element
- * }
- *
- * @param {jQuery|String} field The field name or element
- * @returns {String}
- */
- getDynamicOption: function(option, field) {
- var $field = ('string' === typeof field) ? this.getFieldElements(field) : field,
- value = $field.val();
- // Option can be determined by
- // ... a function
- if ('function' === typeof option) {
- return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]);
- }
- // ... value of other field
- else if ('string' === typeof option) {
- var $f = this.getFieldElements(option);
- if ($f.length) {
- return $f.val();
- }
- // ... return value of callback
- else {
- return $.fn.bootstrapValidator.helpers.call(option, [value, this, $field]);
- }
- }
- return null;
- },
- /**
- * Destroy the plugin
- * It will remove all error messages, feedback icons and turn off the events
- */
- destroy: function() {
- var field, fields, $field, validator, $icon, container, group;
- for (field in this.options.fields) {
- fields = this.getFieldElements(field);
- container = this.options.fields[field].container || this.options.container,
- group = this.options.fields[field].group || this.options.group;
- for (var i = 0; i < fields.length; i++) {
- $field = fields.eq(i);
- $field
- // Remove all error messages
- .data('bv.messages')
- .find('.help-block[data-bv-validator][data-bv-for="' + field + '"]').remove().end()
- .end()
- .removeData('bv.messages')
- // Remove feedback classes
- .parents(group)
- .removeClass('has-feedback has-error has-success')
- .end()
- // Turn off events
- .off('.bv')
- .removeAttr('data-bv-field');
- // Remove feedback icons, tooltip/popover container
- $icon = $field.parents(group).find('i[data-bv-icon-for="' + field + '"]');
- if ($icon) {
- switch (container) {
- case 'tooltip':
- $icon.tooltip('destroy').remove();
- break;
- case 'popover':
- $icon.popover('destroy').remove();
- break;
- default:
- $icon.remove();
- break;
- }
- }
- for (validator in this.options.fields[field].validators) {
- if ($field.data('bv.dfs.' + validator)) {
- $field.data('bv.dfs.' + validator).reject();
- }
- $field.removeData('bv.result.' + validator).removeData('bv.dfs.' + validator);
- }
- }
- }
- // Enable submit buttons
- this.disableSubmitButtons(false);
- this.$form
- .removeClass(this.options.elementClass)
- .off('.bv')
- .removeData('bootstrapValidator')
- // Remove generated hidden elements
- .find('[data-bv-submit-hidden]').remove();
- }
- };
- // Plugin definition
- $.fn.bootstrapValidator = function(option) {
- var params = arguments;
- return this.each(function() {
- var $this = $(this),
- data = $this.data('bootstrapValidator'),
- options = 'object' === typeof option && option;
- if (!data) {
- data = new BootstrapValidator(this, options);
- $this.data('bootstrapValidator', data);
- }
- // Allow to call plugin method
- if ('string' === typeof option) {
- data[option].apply(data, Array.prototype.slice.call(params, 1));
- }
- });
- };
- // The default options
- $.fn.bootstrapValidator.DEFAULT_OPTIONS = {
- // The form CSS class
- elementClass: 'bv-form',
- // Default invalid message
- message: 'This value is not valid',
- // The CSS selector for indicating the element consists the field
- // By default, each field is placed inside the <div class="form-group"></div>
- // You should adjust this option if your form group consists of many fields which not all of them need to be validated
- group: '.form-group',
- //The error messages container. It can be:
- // - 'tooltip' if you want to use Bootstrap tooltip to show error messages
- // - 'popover' if you want to use Bootstrap popover to show error messages
- // - a CSS selector indicating the container
- // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
- // You also can define the message container for particular field
- container: null,
- // The field will not be live validated if its length is less than this number of characters
- threshold: null,
- // Indicate fields which won't be validated
- // By default, the plugin will not validate the following kind of fields:
- // - disabled
- // - hidden
- // - invisible
- //
- // The setting consists of jQuery filters. Accept 3 formats:
- // - A string. Use a comma to separate filter
- // - An array. Each element is a filter
- // - An array. Each element can be a callback function
- // function($field, validator) {
- // $field is jQuery object representing the field element
- // validator is the BootstrapValidator instance
- // return true or false;
- // }
- //
- // The 3 following settings are equivalent:
- //
- // 1) ':disabled, :hidden, :not(:visible)'
- // 2) [':disabled', ':hidden', ':not(:visible)']
- // 3) [':disabled', ':hidden', function($field) {
- // return !$field.is(':visible');
- // }]
- excluded: [':disabled', ':hidden', ':not(:visible)'],
- // Shows ok/error/loading icons based on the field validity.
- // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
- // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
- // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
- //
- // Examples:
- // - Use Glyphicons icons:
- // feedbackIcons: {
- // valid: 'glyphicon glyphicon-ok',
- // invalid: 'glyphicon glyphicon-remove',
- // validating: 'glyphicon glyphicon-refresh'
- // }
- // - Use FontAwesome icons:
- // feedbackIcons: {
- // valid: 'fa fa-check',
- // invalid: 'fa fa-times',
- // validating: 'fa fa-refresh'
- // }
- feedbackIcons: {
- valid: null,
- invalid: null,
- validating: null
- },
- // The submit buttons selector
- // These buttons will be disabled to prevent the valid form from multiple submissions
- submitButtons: '[type="submit"]',
- // The custom submit handler
- // It will prevent the form from the default submission
- //
- // submitHandler: function(validator, form) {
- // - validator is the BootstrapValidator instance
- // - form is the jQuery object presenting the current form
- // }
- submitHandler: null,
- // Live validating option
- // Can be one of 3 values:
- // - enabled: The plugin validates fields as soon as they are changed
- // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
- // - submitted: The live validating is enabled after the form is submitted
- live: 'enabled',
- // Map the field name with validator rules
- fields: null
- };
- // Available validators
- $.fn.bootstrapValidator.validators = {};
- // i18n
- $.fn.bootstrapValidator.i18n = {};
- $.fn.bootstrapValidator.Constructor = BootstrapValidator;
- // Helper methods, which can be used in validator class
- $.fn.bootstrapValidator.helpers = {
- /**
- * Execute a callback function
- *
- * @param {String|Function} functionName Can be
- * - name of global function
- * - name of namespace function (such as A.B.C)
- * - a function
- * @param {Array} args The callback arguments
- */
- call: function(functionName, args) {
- if ('function' === typeof functionName) {
- return functionName.apply(this, args);
- } else if ('string' === typeof functionName) {
- if ('()' === functionName.substring(functionName.length - 2)) {
- functionName = functionName.substring(0, functionName.length - 2);
- }
- var ns = functionName.split('.'),
- func = ns.pop(),
- context = window;
- for (var i = 0; i < ns.length; i++) {
- context = context[ns[i]];
- }
- return context[func].apply(this, args);
- }
- },
- /**
- * Format a string
- * It's used to format the error message
- * format('The field must between %s and %s', [10, 20]) = 'The field must between 10 and 20'
- *
- * @param {String} message
- * @param {Array} parameters
- * @returns {String}
- */
- format: function(message, parameters) {
- if (!$.isArray(parameters)) {
- parameters = [parameters];
- }
- for (var i in parameters) {
- message = message.replace('%s', parameters[i]);
- }
- return message;
- },
- /**
- * Validate a date
- *
- * @param {Number} year The full year in 4 digits
- * @param {Number} month The month number
- * @param {Number} day The day number
- * @param {Boolean} [notInFuture] If true, the date must not be in the future
- * @returns {Boolean}
- */
- date: function(year, month, day, notInFuture) {
- if (isNaN(year) || isNaN(month) || isNaN(day)) {
- return false;
- }
- day = parseInt(day, 10);
- month = parseInt(month, 10);
- year = parseInt(year, 10);
- if (year < 1000 || year > 9999 || month === 0 || month > 12) {
- return false;
- }
- var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
- // Update the number of days in Feb of leap year
- if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
- numDays[1] = 29;
- }
- // Check the day
- if (day <= 0 || day > numDays[month - 1]) {
- return false;
- }
- if (notInFuture === true) {
- var currentDate = new Date(),
- currentYear = currentDate.getFullYear(),
- currentMonth = currentDate.getMonth(),
- currentDay = currentDate.getDate();
- return (year < currentYear
- || (year === currentYear && month - 1 < currentMonth)
- || (year === currentYear && month - 1 === currentMonth && day < currentDay));
- }
- return true;
- },
- /**
- * Implement Luhn validation algorithm
- * Credit to https://gist.github.com/ShirtlessKirk/2134376
- *
- * @see http://en.wikipedia.org/wiki/Luhn
- * @param {String} value
- * @returns {Boolean}
- */
- luhn: function(value) {
- var length = value.length,
- mul = 0,
- prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
- sum = 0;
- while (length--) {
- sum += prodArr[mul][parseInt(value.charAt(length), 10)];
- mul ^= 1;
- }
- return (sum % 10 === 0 && sum > 0);
- },
- /**
- * Implement modulus 11, 10 (ISO 7064) algorithm
- *
- * @param {String} value
- * @returns {Boolean}
- */
- mod11And10: function(value) {
- var check = 5,
- length = value.length;
- for (var i = 0; i < length; i++) {
- check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
- }
- return (check === 1);
- },
- /**
- * Implements Mod 37, 36 (ISO 7064) algorithm
- * Usages:
- * mod37And36('A12425GABC1234002M')
- * mod37And36('002006673085', '0123456789')
- *
- * @param {String} value
- * @param {String} [alphabet]
- * @returns {Boolean}
- */
- mod37And36: function(value, alphabet) {
- alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- var modulus = alphabet.length,
- length = value.length,
- check = Math.floor(modulus / 2);
- for (var i = 0; i < length; i++) {
- check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
- }
- return (check === 1);
- }
- };
- }(window.jQuery));
|