I\'m confused with the Bootstrap 3 implementation of form validation. I\'m new to Bootstrap, and I cannot seem to get the form validation working with a form that does not incl
I have done some research, and I now know that the form validation I was seeing was not a function of Bootstrap but a new CSS3 / HTML5 feature. I don't believe it is possible (without JS) to perform this form validation unless the submit button is enclosed within the form. Here is an example of what was not working:
http://jsfiddle.net/hTPY7/1112/
Here's an example of how it was fixed:
http://jsfiddle.net/hTPY7/1113/
The <form>
element needs to surround more than just the form, but also surround the Bootstrap modal divs.
Here is another post which summarizes my problem well:
HTML5 form validation for AJAX button submit
we need to use some kind of external library or custom code to add validation rules, which will enable us to add validation classes to form. I don't think there is other way around.
Example:
http://jsfiddle.net/mapb_1990/hTPY7/9/
HTML:
<form>
<div class="form-group">
<label class="control-label" for="firstname">Nome:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input class="form-control" placeholder="Insira o seu nome próprio" name="firstname" type="text" />
</div>
</div>
<div class="form-group">
<label class="control-label" for="lastname">Apelido:</label>
<div class="input-group">
<span class="input-group-addon">€</span>
<input class="form-control" placeholder="Insira o seu apelido" name="lastname" type="text" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JS:
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
If you accept HTML5, with it's form validation, then it's very simple (no javascript required):
<form id="my-awesome-form">
...
</form>
...
<button type="submit" form="my-awesome-form">Submit</button>
Source: https://www.w3schools.com/tags/att_button_form.asp
Coverage is pretty decent: https://caniuse.com/#feat=form-attribute