This site contains the document for old version. Please upgrade to the latest version v1.0.0

News

The latest news about FormValidation

Best jQuery practices

This post introduces best jQuery practices you should follow:

Loading from CDN

Instead of storing jQuery on your server, choose to load it from popular CDNs. It will decrease the page loading time.

<!-- Don't -->
<script src="/vendor/jquery/jquery.min.js"></script>

<!-- Do -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Below is the list of popular CDNs which you can find jQuery on:

There are some good practices, not only for jQuery, but also for other CSS, JS libraries when loading them from CDN:

Provide a fallback version in your server if loading from CDN fails

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write("<script src='/vendor/jquery/jquery.min.js'>\x3C/script>");</script>

Choosing the compressed version

<!-- Don't -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>

<!-- Do -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Placing the script at the bottom of page

<!doctype html>
<head>
    ...
    <!-- Don't -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
    ...
    <!-- Do -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

Using protocol-relative URL

Leaving http: or https: out of the URL. By doing this, the browser will choose to load the https URL of script if your page is severed under https.

<!-- Don't -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- Do -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Shorthand for the ready event

// Usual way
$(document).ready(function() {
    ...
});

// The shorthand
$(function() {

});

Naming jQuery object starting with $

With this naming convention, we can know whether or not a variable is a jQuery object.

// Don't
var form = $('#contactForm');

// Do
var $form = $('#contactForm');

Using $this

Use $this variable at the beginning anonymous functions, for example, inside an each loop:

// Don't
$('li').each(function() {
    $(this).on('click', function() {
        $(this).addClass('active');
    });
});

// Do
$('li').each(function() {
    var $this = $(this);
    $this.on('click', function() {
        $this.addClass('active');
    });
});

Someone prefer to use that or self. Don't forget to prefix with $ if it's jQuery object.

Caching jQuery objects

If a jQuery object is used multiple times, caching it will save the performance of script.

// Don't
$('.menu li').each(function() { ... });
$('.menu li').each(function() { ... });

// Do
var $items = $('.menu li');
$items.each(function() { ... });

// Reuse it
$items.each(function() { ... });

Chaining method

Chaining method is one of most powerful features of jQuery. It allows us to call multiple methods at the same time.

"Write less, do more", the jQuery's slogan, is perfectly right in this case
// Don't
var $a = $('#about');
$a.hide();
$a.addClass();
$a.fadeIn();
$a.hide();

// Do
$('#about').hide().addClass().fadeIn().hide();

// Better
// Add line-break and indent for readability
$('#about')
    .hide()
    .addClass()
    .fadeIn()
    .hide();

Creating new element

When creating new element, try to use jQuery methods to manipulate the element instead of giving full HTML code.

// Don't
var $hidden = $('<input class="form-control" type="hidden" name="foo" value="bar" />').appendTo('#form');

// Do
var $hidden = $('<input/>')
                .addClass('form-control')
                .attr('type', 'hidden')
                .attr('name', 'foo')
                .val('bar')
                .appendTo('#form');

// Or
var $hidden = $('<input/>', {
                    class: 'form-control',
                    type: 'hidden',
                    name: 'foo',
                    value: 'bar'
                })
                .appendTo('#form');

Don't mix CSS with jQuery

Don't set the CSS styles for element directly. Using CSS class instead.

// Don't
$('#button').css({
    'background-color': '#5cb85c',
    'border-color': '#4cae4c'
});

// Do
.success {
    background-color: #5cb85c;
    border-color: #4cae4c;
}

$('#button').addClass('success');

Optimizing selectors

Using ID selector

To retrieve the element by given ID, jQuery uses native document.getElementById() method which is faster than using Sizzle.

Sizzle is a pure-JavaScript CSS selector engine used by jQuery
// Don't
$('#wrapper #inner');
$('div#inner');
$('.wrapper #inner');

// Do
$('#inner');

Using ID-based selector

// Don't
$('#container .row');

// Faster
$('#container').find('.row');

Specificity

Be specific on the right-hand side of your selector, and less specific on the left.

// Unoptimized
$('div.data .gonzalez');

// Optimized
$('.data td.gonzalez');

Avoid the universal selectors

// Slow
$('div.container > *');

// Faster
$('.container').children();

Avoid implied universal selectors

It's recommended to prefix a pseudo-class selectors (beginning with :) with a tag name or other selector. Otherwise, the universal selector (*) is still implied.

// Don't
$('.category :radio');

// Do
$('.category input:radio');

Using filtering methods instead of pseudo selectors

When possible, use jQuery filter method instead of pseudo selectors. jQuery then uses querySelectorAll method which is faster than using Sizzle methods.

// Don't
$('.item:first')

// Do
$('.item').eq(0)

Don't use JS inline to bind events

Always using jQuery to bind events:

<!-- Don't -->
<button id="saveButton" onclick="javascript: save();">Save</button>

// Do
$('#saveButton').on('click', function() {
    ...
});

Using custom namespace for events

By using custom namespace, you can easily unbind the exact event without affecting to other event handlers which are bound to the element.

$('#saveButton').on('click.bv', function() {
    ...
});

// Later, it's possible to unbind the event handler
$('#saveButton').off('click.bv');

Don't put all parameters in Ajax URL

When sending data to remote URL using an Ajax request, use data option to send them instead of putting in the URL.

// Don't
$.ajax({
    url: '/remote/url?param1=value1&amp;param2=value2...'
}});

// Do
$.ajax({
    url: '/remote/url',
    data: {
        param1: 'value1',
        param2: 'value2'
        ...
    }
});

In the case the parameter might be too long (the article's content, for example), consider to use the POST method for both Ajax requests and the back-end.

Internet Explorer 8 (and earlier) limits 2083 characters in URL

References

BootstrapValidator v0.5.3 Released

New features

Improvements

  • #823: The color validator only accepts 6 hex character values when using HTML 5 type='color' attribute
  • #864: Comma separator handling in greaterThan, lessThan validators, thanks to @mgibas
  • #999, #1048: Replace ',' with '.' to validate decimal numbers correct, thanks to @johanronn77
  • #1002: Put tooltip/popover on bottom if there is not enough space on top, thanks to @jazzzz
  • #1015: The remote validator allows to set data options via HTML attributes, thanks to @jazzzz
  • #1017: Enable validator when setting data-bv-validatorname="data-bv-validatorname", thanks to @jazzzz
  • #1026: Requires jQuery 1.9.1 or higher

Bug fixes

  • #343, #481, #1045: Fix double submit with defered validators, thanks to @jazzzz
  • #933, #959, #1047: Tooltip/popover isn't destroyed when the field is valid
  • #991: The field is validated only one time when setting trigger: 'blur', container: 'tooltip'
  • #1014: Fix isValidField() and validateField() methods for fields without validators, thanks to @jazzzz
  • #1050: Fix the issue when using multiple fields with same name, the tooltip of the last element is always shown
  • #1055, #1063: The error.field.bv event isn't triggered if verbose is set to false, thanks to @shineability
  • #1057, #1063: The verbose option for field doesn't override the form level, thanks to @shineability

Document

Language packages

  • #827: Update Dutch language package, thanks to @JvanderHeide
  • #829: Update Swedish language package, thanks to @ulsa
  • #834: Update Ukrainian and Russian language packages, thanks to @oleg-voloshyn
  • #835: Update Belgium (French) language package, thanks to @neilime
  • #836: Update French language package, thanks to @neilime
  • #837: Update Bulgarian language package, thanks to @mraiur
  • #846: Update simplified Chinese language package, thanks to @shamiao
  • #849: Update Serbian language package, thanks to @markocrni
  • #850, #851: Update Danish language package, thanks to @Djarnis
  • #869: Update Polish language package, thanks to @grzesiek
  • #870: Update Traditional Chinese language package, thanks to @tureki
  • #871: Update Czech language package, thanks to @cuchac
  • #872: Update Indonesian language package, thanks to @egig
  • #879: Update Romanian language package, thanks to @filipac
  • #880: Update Belgium (Dutch) language package, thanks to @dokterpasta
  • #881: Update Italian language package, thanks to @maramazza
  • #882: Update Spanish language package, thanks to @vadail
  • #891: Update Portuguese (Brazil) language package, thanks to @dgmike
  • #893: Fix country name of Dominican Republic, thanks to @sventech
  • #900: Update Persian (Farsi) language package, thanks to @i0
  • #903: Update Hungarian language package, thanks to @blackfyre
  • #910: Update Greek language package, thanks to @pRieStaKos
  • #913: Update Thai language package, thanks to @figgaro
  • #915: Update Turkish language package, thanks to @CeRBeR666
  • #961: Update Chilean Spanish language package, thanks to @marceloampuerop6
  • #967: Add Hebrew language package, thanks to @yakidahan
  • #974: Add Albanian language package, thanks to @desaretiuss
  • #1025: Fix French emailAddress message, thanks to @jazzzz
  • #1051: Add Portuguese language package, thanks to @rtbfreitas

Contributors

Thanks to 40 contributors:

Download

BootstrapValidator v0.5.2 Released

New features

  • #480: Add verbose option, thanks to @mbezhanov
  • #542, #666: Add blank validator, thanks to @bermo
  • #617: Add init and destroy methods to validator
  • #724: Add Venezuelan VAT number (RIF) validator, thanks to @paquitodev
  • #739: Add China phone number validator, thanks to @caijh
  • #743: Add Venezuela phone number validator, thanks to @paquitodev
  • #760: Add Romania phone number validator, thanks to @adrian-dks
  • #761: Add Romania postal code validator, thanks to @adrian-dks
  • #785: Add Denmark phone number validator, thanks to @emilchristensen
  • #787: Add Thailand phone number and ID validator, thanks to @figgaro
  • #793, #798: Add Chinese citizen ID validator, thanks to @shamiao
  • #802: Add Russia phone number validator, thanks to @cylon-v. #816: Improved by @stepin
  • #816: Add Russian postal code validator, thanks to @stepin
  • #867: Add Czech and Slovakia phone number and postal code validators, thanks to @cuchac

Changes

  • #753: Change the default type of remote validator to GET

Improvements

  • #249, #574, #669: Add delay option to the remote validator, thanks to @q-state
  • #345, #454: The different validator allows more than a 2-way comparison, thanks to @AlaskanShade
  • #557, #569: The container option can be defined by a callback, thanks to @mattrick
  • #570: Use CSS classes instead of inline styling to fix icons with input-group, thanks to @dlcrush
  • #578, #813: The stringLength validator supports HTML 5 minlength attribute, thanks to @emilchristensen
  • #675: The emailAddress validator accepts multiple email addresses, thanks to @kenny-evitt
  • #716, #765: Reuse data returned by callback, remote, custom validators
  • #734: The uri validator adds support for custom protocol, thanks to @bcamarneiro
  • #737: Support VAT number without prefixing by country code
  • #754: Support latest Bootstrap when using tooltip/popover to show the message
  • #783: Improve behaviour of the different validator
  • #792: Add "BootstrapValidator's JavaScript requires jQuery" warning, thanks to @Arkni
  • #803: Add minSize option for the file validator, thanks to @Arkni
  • #824: Add phone number validator test suite

Bug fixes

  • #611, #703: Tabs get red even form is valid
  • #612, #740, #741: Fix the emailAddress issue which email@server is not valid email address, thanks to @kromit
  • #687, #711: Keep disabled validators VALID, thanks to @talberti
  • #725: Fix the issue when adding field which does not exist but is already set in "fields" option
  • #732: Fix the issue when removing the radio or checkbox field
  • #746: The form is still submitted when clicking on submit button which is set onclick="return false;"
  • #758: Using notEmpty validator with type="number"
  • #759, #764: The tooltip/popover isn't shown if there is disabled validator. The tooltip/popover is shown automatically when the field gets the focus, thanks to @leedorian
  • #797, #799: Can't validate ipv4 and ipv6 at the same time. Add ip validator test suite, thanks to @Arkni
  • #816: Fix Russian VAT number validator, thanks to @stepin
  • #832: The form won't be validated if the submit button contains a HTML tag

Document

Language packages

  • #706: Japanese language package, thanks to @tsuyoshifujii
  • #712: Swedish language package, thanks to @ulsa
  • #727: Belgium (French) language package, thanks to @neilime
  • #729: Persian (Farsi) language package, thanks to @i0
  • #779: Romanian language package, thanks to @filipac
  • #787: Thai language package, thanks to @figgaro
  • #788: Fully re-translated Simplified Chinese language package, thanks to @shamiao
  • #795: Re-translated traditional Chinese language package, thanks to @tureki
  • #802: Russian language package, thanks to @cylon-v. #816: Improved by @stepin
  • #806: Ukrainian language package, thanks to @oleg-voloshyn
  • #840: Serbian language package, thanks to @markocrni
  • #856: Norwegian language package, thanks to @trondulseth
  • #868: Indonesian language package, thanks to @egig

Upgrade from v0.5.x to v0.5.2

If you don't use the remote validator, just download v0.5.2 package and override the CSS/JS bundle.

Otherwise, please indicate the type option when using remote validator:

$(form).bootstrapValidator({
    fields: {
        username: {
            message: 'The username is not valid',
            validators: {
                // The validator will create an Ajax request
                // sending { username: 'its value' } to the back-end
                remote: {
                    message: 'The username is not available',
                    url: '/path/to/backend/',
                    type: 'GET'     // or 'POST'
                }
            }
        }
    }
});

Contributors

Thanks to 30 contributors:

Download

BootstrapValidator v0.5.1 Released

New features

Improvements

  • #502: Allowing sites without TLD to pass URI validation, thanks to @troymccabe
  • #549, #600: Change the CSS/JS path in demo/remote.html and demo/message.html, thanks to @leegtang, @Arkni
  • #604: Fix the demo/date.html and demo/tab.html examples, thanks to @Arkni
  • #609: Add content-type header for demo/remote.php, thanks to @etorres
  • #661: Add headers option to the remote validator, thanks to @ryan2049
  • #664: Fix the feedback icon position for Bootstrap 3.2
  • #683: Force the format option to be YYYY-MM-DD when using <input type="date" />
  • #698: Ignore type checking if the file type is empty

Bug fixes

  • #284, #294, #441, #516: The HTML 5 <input type="number" /> input allows to input non-digits characters
  • #548: Fix the issue when using different validator to compare with not existing field
  • #550, #551: Cannot validate against both ipv4 and ipv6 at the same time, thanks to @beeglebug
  • #588: Don't use min, max attributes (greaterThan, lessThan validators) for <input type="date" />
  • #665: The submitButtons option doesn't work correctly
  • #672: The zipCode validator throw an exception when passing not supported country code
  • #681: Fix the date validator issue where one of date/month/year or hours/minutes/seconds is prefixed by zero
  • #692: The remote validator can't set the type option via HTML attribute
  • #700: The between, greaterThan, lessThan validators accept param which isn't number

Language packages

  • #396: German language package, thanks to @logemann
  • #400: Italian language package, thanks to @maramazza
  • #474: Hungarian language package, thanks to @blackfyre
  • #478: Simplified and traditional Chinese language package, thanks to @tureki
  • #494: Chilean Spanish language package, thanks to @marceloampuerop6
  • #503: French language package, thanks to @dlucazeau
  • #505: Czech language package, thanks to @AdwinTrave
  • #507: Polish language package, thanks to @grzesiek. #624: Typos fixed by @lukaszbanasiak
  • #517: Belgium (Dutch) language package, thanks to @dokterpasta
  • #527: Bulgarian language package, thanks to @mraiur
  • #534: Turkish language package, thanks to @CeRBeR666
  • #536: Spanish language package, thanks to @vadail
  • #544: Greek language package, thanks to @pRieStaKos
  • #545: Portuguese (Brazil) language package, thanks to @marcuscarvalho6
  • #598: Danish language package, thanks to @Djarnis
  • #674, #677: Dutch language package, thanks to @jvanderheide
  • #679: Add Arabic language package, thanks to @Arkni

Contributors

Thank to the contributor:

Download

Upgrading to v0.5.0

From v0.5.0, we remove the submitHandler option. In v0.5.0, use the success.form.bv event instead.

In v0.4.5 and earlier versions:

$(form).bootstrapValidator({
    submitHandler: function(form, validator, submitButton) {
        ...
    }
});

In v0.5.0:

$(form)
    .bootstrapValidator({
        // Removing submitHandler option
    })
    .on('success.form.bv', function(e) {
        // Prevent form submission
        e.preventDefault();

        var $form        = $(e.target),
            validator    = $form.data('bootstrapValidator'),
            submitButton = validator.getSubmitButton();

        // Do whatever you want here ...
    });

Download