Hướng dẫn bootstrap 3 form validation

Examples and usage guidelines for form control styles, layout options, and custom components for creating a wide variety of forms.

Overview

Bootstrap’s form controls expand on our Rebooted form styles with classes. Use these classes to opt into their customized displays for a more consistent rendering across browsers and devices.

Be sure to use an appropriate type attribute on all inputs [e.g., email for email address or number for numerical information] to take advantage of newer input controls like email verification, number selection, and more.

Here’s a quick example to demonstrate Bootstrap’s form styles. Keep reading for documentation on required classes, form layout, and more.


  
    Email address
    
    We'll never share your email with anyone else.
  
Password Check me out Submit

Form controls

Textual form controls—like s, s, and s—are styled with the .form-control class. Included are styles for general appearance, focus state, sizing, and more.

Be sure to explore our custom forms to further style s.

Email address

Example select

Example multiple select

Example textarea


  
    Email address
    
  
  
    Example select
    
      1
      2
      3
      4
      5
    
  
  
    Example multiple select
    
      1
      2
      3
      4
      5
    
  
  
    Example textarea
    
  

For file inputs, swap the .form-control for .form-control-file.


  
    Example file input
    
  

Sizing

Set heights using classes like .form-control-lg and .form-control-sm.




  Large select


  Default select


  Small select

Readonly

Add the readonly boolean attribute on an input to prevent modification of the input’s value. Read-only inputs appear lighter [just like disabled inputs], but retain the standard cursor.

Readonly plain text

If you want to have elements in your form styled as plain text, use the .form-control-plaintext class to remove the default form field styling and preserve the correct margin and padding.


  
    Email
    
      
    
  
  
    Password
    
      
    
  


  
    Email
    
  
  
    Password
    
  
  Confirm identity

Checkboxes and radios

Default checkboxes and radios are improved upon with the help of .form-check, a single class for both input types that improves the layout and behavior of their HTML elements. Checkboxes are for selecting one or several options in a list, while radios are for selecting one option from many.

Disabled checkboxes and radios are supported, but to provide a not-allowed cursor on hover of the parent , you’ll need to add the disabled attribute to the .form-check-input. The disabled attribute will apply a lighter color to help indicate the input’s state.

Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our s and s are sibling elements as opposed to an within a . This is slightly more verbose as you must specify id and for attributes to relate the and .

Default [stacked]

By default, any number of checkboxes and radios that are immediate sibling will be vertically stacked and appropriately spaced with .form-check.

Default checkbox

Disabled checkbox


  
  
    Default checkbox
  


  
  
    Disabled checkbox
  

Default radio

Second default radio

Disabled radio


  
  
    Default radio
  


  
  
    Second default radio
  


  
  
    Disabled radio
  

Inline

Group checkboxes or radios on the same horizontal row by adding .form-check-inline to any .form-check.


  
  1


  
  2


  
  3 [disabled]


  
  1


  
  2


  
  3 [disabled]

Without labels

Add .position-static to inputs within .form-check that don’t have any label text. Remember to still provide some form of label for assistive technologies [for instance, using aria-label].


  


  

Layout

Since Bootstrap applies display: block and width: 100% to almost all our form controls, forms will by default stack vertically. Additional classes can be used to vary this layout on a per-form basis.

Form groups

The .form-group class is the easiest way to add some structure to forms. It provides a flexible class that encourages proper grouping of labels, controls, optional help text, and form validation messaging. By default it only applies margin-bottom, but it picks up additional styles in .form-inline as needed. Use it with s,

s, or nearly any other element.


  
    Example label
    
  
Another label

Form grid

More complex forms can be built using our grid classes. Use these for form layouts that require multiple columns, varied widths, and additional alignment options.


  
    
      
    
    
      
    
  

Form row

You may also swap .row for .form-row, a variation of our standard grid row that overrides the default column gutters for tighter and more compact layouts.


  
    
      
    
    
      
    
  

More complex layouts can also be created with the grid system.


  
    
      Email
      
    
    
      Password
      
    
  
  
    Address
    
  
  
    Address 2
    
  
  
    
      City
      
    
    
      State
      
        Choose...
        ...
      
    
    
      Zip
      
    
  
  
    
      
      
        Check me out
      
    
  
  Sign in

Horizontal form

Create horizontal forms with the grid by adding the .row class to form groups and using the .col-*-* classes to specify the width of your labels and controls. Be sure to add .col-form-label to your s as well so they’re vertically centered with their associated form controls.

At times, you maybe need to use margin or padding utilities to create that perfect alignment you need. For example, we’ve removed the padding-top on our stacked radio inputs label to better align the text baseline.


  
    Email
    
      
    
  
  
    Password
    
      
    
  
  
    
      Radios
      
        
          
          
            First radio
          
        
        
          
          
            Second radio
          
        
        
          
          
            Third disabled radio
          
        
      
    
  
  
    Checkbox
    
      
        
        
          Example checkbox
        
      
    
  
  
    
      Sign in
    
  

Horizontal form label sizing

Be sure to use .col-form-label-sm or .col-form-label-lg to your s or s to correctly follow the size of .form-control-lg and .form-control-sm.


  
    Email
    
      
    
  
  
    Email
    
      
    
  
  
    Email
    
      
    
  

Column sizing

As shown in the previous examples, our grid system allows you to place any number of .cols within a .row or .form-row. They’ll split the available width equally between them. You may also pick a subset of your columns to take up more or less space, while the remaining .cols equally split the rest, with specific column classes like .col-7.


  
    
      
    
    
      
    
    
      
    
  

Auto-sizing

The example below uses a flexbox utility to vertically center the contents and changes .col to .col-auto so that your columns only take up as much space as needed. Put another way, the column sizes itself based on the contents.


  
    
      Name
      
    
    
      Username
      
        
          @
        
        
      
    
    
      
        
        
          Remember me
        
      
    
    
      Submit
    
  

You can then remix that once again with size-specific column classes.


  
    
      Name
      
    
    
      Username
      
        
          @
        
        
      
    
    
      
        
        
          Remember me
        
      
    
    
      Submit
    
  

And of course custom form controls are supported.


  
    
      Preference
      
        Choose...
        One
        Two
        Three
      
    
    
      
        
        Remember my preference
      
    
    
      Submit
    
  

Inline forms

Use the .form-inline class to display a series of labels, form controls, and buttons on a single horizontal row. Form controls within inline forms vary slightly from their default states.

You may need to manually address the width and alignment of individual form controls with spacing utilities [as shown below]. Lastly, be sure to always include a with each form control, even if you need to hide it from non-screenreader visitors with .sr-only.


  Name
  

  Username
  
    
      @
    
    
  

  
    
    
      Remember me
    
  

  Submit

Custom form controls and selects are also supported.


  Preference
  
    Choose...
    One
    Two
    Three
  

  
    
    Remember my preference
  

  Submit

Alternatives to hidden labels

Assistive technologies such as screen readers will have trouble with your forms if you don’t include a label for every input. For these inline forms, you can hide the labels using the .sr-only class. There are further alternative methods of providing a label for assistive technologies, such as the aria-label, aria-labelledby or title attribute. If none of these are present, assistive technologies may resort to using the placeholder attribute, if present, but note that use of placeholder as a replacement for other labelling methods is not advised.

Help text

Block-level help text in forms can be created using .form-text [previously known as .help-block in v3]. Inline help text can be flexibly implemented using any inline HTML element and utility classes like .text-muted.

Associating help text with form controls

Help text should be explicitly associated with the form control it relates to using the aria-describedby attribute. This will ensure that assistive technologies—such as screen readers—will announce this help text when the user focuses or enters the control.

Help text below inputs can be styled with .form-text. This class includes display: block and adds some top margin for easy spacing from the inputs above.

Password Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.

Password


  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.

Inline text can use any typical inline HTML element [be it a , , or something else] with nothing more than a utility class.


  
    Password
    
    
      Must be 8-20 characters long.
    
  

Disabled forms

Add the disabled boolean attribute on an input to prevent user interactions and make it appear lighter.

Add the disabled attribute to a to disable all the controls within.


  
    
      Disabled input
      
    
    
      Disabled select menu
      
        Disabled select
      
    
    
      
      
        Can't check this
      
    
    Submit
  

Caveat with anchors

By default, browsers will treat all native form controls [, and elements] inside a as disabled, preventing both keyboard and mouse interactions on them. However, if your form also includes elements, these will only be given a style of pointer-events: none. As noted in the section about disabled state for buttons [and specifically in the sub-section for anchor elements], this CSS property is not yet standardized and isn’t fully supported in Opera 18 and below, or in Internet Explorer 10, and won’t prevent keyboard users from being able to focus or activate these links. So to be safe, use custom JavaScript to disable such links.

Cross-browser compatibility

While Bootstrap will apply these styles in all browsers, Internet Explorer 11 and below don’t fully support the disabled attribute on a . Use custom JavaScript to disable the fieldset in these browsers.

Validation

Provide valuable, actionable feedback to your users with HTML5 form validation–available in all our supported browsers. Choose from the browser default validation feedback, or implement custom messages with our built-in classes and starter JavaScript.

We highly recommend custom validation styles as native browser defaults are not announced to screen readers.

How it works

Here’s how form validation works with Bootstrap:

With that in mind, consider the following demos for our custom form validation styles, optional server side classes, and browser defaults.

Custom styles

For custom Bootstrap form validation messages, you’ll need to add the novalidate boolean attribute to your . This disables the browser default feedback tooltips, but still provides access to the form validation APIs in JavaScript. Try to submit the form below; our JavaScript will intercept the submit button and relay feedback to you.

When attempting to submit, you’ll see the :invalid and :valid styles applied to your form controls.


  
    
      First name
      
      
        Looks good!
      
    
    
      Last name
      
      
        Looks good!
      
    
    
      Username
      
        
          @
        
        
        
          Please choose a username.
        
      
    
  
  
    
      City
      
      
        Please provide a valid city.
      
    
    
      State
      
      
        Please provide a valid state.
      
    
    
      Zip
      
      
        Please provide a valid zip.
      
    
  
  
    
      
      
        Agree to terms and conditions
      
      
        You must agree before submitting.
      
    
  
  Submit form



// Example starter JavaScript for disabling form submissions if there are invalid fields
[function[] {
  'use strict';
  window.addEventListener['load', function[] {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName['needs-validation'];
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call[forms, function[form] {
      form.addEventListener['submit', function[event] {
        if [form.checkValidity[] === false] {
          event.preventDefault[];
          event.stopPropagation[];
        }
        form.classList.add['was-validated'];
      }, false];
    }];
  }, false];
}][];

Browser defaults

Not interested in custom validation feedback messages or writing JavaScript to change form behaviors? All good, you can use the browser defaults. Try submitting the form below. Depending on your browser and OS, you’ll see a slightly different style of feedback.

While these feedback styles cannot be styled with CSS, you can still customize the feedback text through JavaScript.


  
    
      First name
      
    
    
      Last name
      
    
    
      Username
      
        
          @
        
        
      
    
  
  
    
      City
      
    
    
      State
      
    
    
      Zip
      
    
  
  
    
      
      
        Agree to terms and conditions
      
    
  
  Submit form

Server side

We recommend using client side validation, but in case you require server side, you can indicate invalid and valid form fields with .is-invalid and .is-valid. Note that .invalid-feedback is also supported with these classes.


  
    
      First name
      
      
        Looks good!
      
    
    
      Last name
      
      
        Looks good!
      
    
    
      Username
      
        
          @
        
        
        
          Please choose a username.
        
      
    
  
  
    
      City
      
      
        Please provide a valid city.
      
    
    
      State
      
      
        Please provide a valid state.
      
    
    
      Zip
      
      
        Please provide a valid zip.
      
    
  
  
    
      
      
        Agree to terms and conditions
      
      
        You must agree before submitting.
      
    
  
  Submit form

Supported elements

Our example forms show native textual s above, but form validation styles are available for our custom form controls, too.


  
    
    Check this custom checkbox
    Example invalid feedback text
  

  
    
    Toggle this custom radio
  
  
    
    Or toggle this other custom radio
    More example invalid feedback text
  

  
    
      Open this select menu
      One
      Two
      Three
    
    Example invalid custom select feedback
  

  
    
    Choose file...
    Example invalid custom file feedback
  

Tooltips

If your form layout allows it, you can swap the .{valid|invalid}-feedback classes for .{valid|invalid}-tooltip classes to display validation feedback in a styled tooltip. Be sure to have a parent with position: relative on it for tooltip positioning. In the example below, our column classes have this already, but your project may require an alternative setup.


  
    
      First name
      
      
        Looks good!
      
    
    
      Last name
      
      
        Looks good!
      
    
    
      Username
      
        
          @
        
        
        
          Please choose a unique and valid username.
        
      
    
  
  
    
      City
      
      
        Please provide a valid city.
      
    
    
      State
      
      
        Please provide a valid state.
      
    
    
      Zip
      
      
        Please provide a valid zip.
      
    
  
  Submit form

Custom forms

For even more customization and cross browser consistency, use our completely custom form elements to replace the browser defaults. They’re built on top of semantic and accessible markup, so they’re solid replacements for any default form control.

Checkboxes and radios

Each checkbox and radio is wrapped in a

with a sibling to create our custom control and a for the accompanying text. Structurally, this is the same approach as our default .form-check.

We use the sibling selector [~] for all our states—like :checked—to properly style our custom form indicator. When combined with the .custom-control-label class, we can also style the text for each item based on the ’s state.

We hide the default with opacity and use the .custom-control-label to build a new custom form indicator in its place with ::before and ::after. Unfortunately we can’t build a custom one from just the because CSS’s content doesn’t work on that element.

In the checked states, we use base64 embedded SVG icons from Open Iconic. This provides us the best control for styling and positioning across browsers and devices.

Checkboxes

Check this custom checkbox


  
  Check this custom checkbox

Custom checkboxes can also utilize the :indeterminate pseudo class when manually set via JavaScript [there is no available HTML attribute for specifying it].

Check this custom checkbox

If you’re using jQuery, something like this should suffice:

$['.your-checkbox'].prop['indeterminate', true]

Radios

Toggle this custom radio

Or toggle this other custom radio


  
  Toggle this custom radio


  
  Or toggle this other custom radio

Inline

Toggle this custom radio

Or toggle this other custom radio


  
  Toggle this custom radio


  
  Or toggle this other custom radio

Disabled

Custom checkboxes and radios can also be disabled. Add the disabled boolean attribute to the and the custom indicator and label description will be automatically styled.

Check this custom checkbox

Toggle this custom radio


  
  Check this custom checkbox



  
  Toggle this custom radio

Custom menus need only a custom class, .custom-select to trigger the custom styles.


  Open this select menu
  One
  Two
  Three

You may also choose from small and large custom selects to match our similarly sized text inputs.


  Open this select menu
  One
  Two
  Three



  Open this select menu
  One
  Two
  Three

The multiple attribute is also supported:


  Open this select menu
  One
  Two
  Three

As is the size attribute:


  Open this select menu
  One
  Two
  Three

File browser

The file input is the most gnarly of the bunch and requires additional JavaScript if you’d like to hook them up with functional Choose file… and selected file name text.


  
  Choose file

We hide the default file via opacity and instead style the . The button is generated and positioned with ::after. Lastly, we declare a width and height on the for proper spacing for surrounding content.

Translating or customizing the strings

The :lang[] pseudo-class is used to allow for translation of the “Browse” text into other languages. Override or add entries to the $custom-file-text Sass variable with the relevant language tag and localized strings. The English strings can be customized the same way. For example, here’s how one might add a Spanish translation [Spanish’s language code is es]:

$custom-file-text: [
  en: "Browse",
  es: "Elegir"
];

Here’s lang[es] in action on the custom file input for a Spanish translation:


  
  Seleccionar Archivo

You’ll need to set the language of your document [or subtree thereof] correctly in order for the correct text to be shown. This can be done using the lang attribute on the element or the Content-Language HTTP header, among other methods.

Chủ Đề