(v4) Form validation
Created by: tmentink
I love how easy it is to style forms with bootstrap but I felt that the validation classes could be improved a bit. For those of you who want to jump straight to the demo, here you go.
Lets look at the first validation example in the docs.
Currently we would have to do the following steps in javascript to toggle between the different validation states:
- Remove the previous .has-* from the parent element and then apply the new class
- Remove the previous .form-control-* from the input and then apply the new class
- Overwrite the inner HTML of the .form-control-feedback with the new message
I think that we could eliminate step 2 and 3 by making the following changes:
- collapse .form-control-* into a single class that changes its background-image based upon the .has-* of its parent
- set .form-control-feedback content to data attributes based upon the .has-* of its parent
_forms.scss:
.form-control-feedback {
margin-top: $form-feedback-margin-top;
&:after {
display: block;
content: "";
opacity: 0;
}
}
.has-success,
.has-warning,
.has-danger {
.form-control.feedback-icon {
padding-right: ($input-padding-x * 3);
background-repeat: no-repeat;
background-position: center right ($input-height / 4);
background-size: ($input-height / 2) ($input-height / 2);
}
}
// Form validation states
.has-success {
@include form-control-validation($brand-success);
.form-control.feedback-icon {
background-image: $form-icon-success;
}
.form-control-feedback:after {
content: attr(data-success);
opacity: 1;
}
}
.has-warning {
@include form-control-validation($brand-warning);
.form-control.feedback-icon {
background-image: $form-icon-warning;
}
.form-control-feedback:after {
content: attr(data-warning);
opacity: 1;
}
}
.has-danger {
@include form-control-validation($brand-danger);
.form-control.feedback-icon {
background-image: $form-icon-danger;
}
.form-control-feedback:after {
content: attr(data-danger);
opacity: 1;
}
}
I also added two new transitions to be in sync with .form-control
_variables.scss:
$input-group-addon-transition : background-color ease-in-out .15s, border-color ease-in-out .15s !default;
$form-feedback-transition : opacity ease-in-out .15s, color ease-in-out .15s !default;
_forms.scss:
.form-control-feedback {
&:after {
@include transition($form-feedback-transition);
}
}
_input-group.scss:
.input-group-addon {
@include transition($input-group-addon-transition);
}
This is probably outside the scope of bootstrap but I also wrote some javascript that leverages HTML5 validation attributes to apply the appropriate .has-*. I plan on expanding this to include a pattern for .has-warning but this jsbin gets the general idea across.