Question:
I'm using http://www.bootstraptoggle.com/ , a simple true or false toggle.
Here is the code:
View:
<form id="myform">
@Html.CheckBoxFor(model => model.Permitir, new { id = "toggle1", data_on = "Sim", data_off = "Não", data_toggle = "toggle", data_class = "fast", data_size = "mini", data_onstyle = "success", data_offstyle = "danger" })
@Html.ValidationMessageFor(model => model.Permitir, "", new { @class = "text-danger" })
</form>
<input type="submit" class="btn btn-success" value="Adicionar" />
Javascript:
$(function () {
$('#toggle1').bootstrapToggle();
$('#toggle2').bootstrapToggle();
$('#toggle3').bootstrapToggle();
$('#toggle4').bootstrapToggle();
});
$("#myform").validate({
ignore: ":hidden",
rules: {
Permitir: { required: true}
},
messages: {
Permitir: "<span style=\"color: #a94442;\">Campo Permitir é obrigatório *</span>"
}, ....
The "Allow" field is mandatory. It needs to stay true. Validate is not working. Any solution ?
Answer:
When using Bootstrap Toggle there is a problem: the messages don't appear ( this plugin adds a div that obfuscates the validation message) not getting the answer of validated or not , but it has a friendly way to show all errors with errorLabelContainer , example Minimum:
Html
<form id="myform">
<div>
<input type="text" class="form-control" name="Nome" id="Nome" />
</div>
<br />
<div>
<input type="checkbox"
name="Permitir" id="Permitir"
checked data-toggle="toggle"
data-size="large"
data-width="75" data-height="55"/>
</div>
<br />
<button class="btn btn-success">Enviar</button>
</form>
<ul id="errors">
</ul>
Javascript
$("#myform").validate({
ignore: [],
rules: {
Nome: {
required: true
},
Permitir: {
required: true
}
},
messages: {
Nome: { required: "Nome é obrigatório" },
Permitir: { required: "Permitir é obrigatório"}
},
errorLabelContainer: "#errors",
errorElement: "li"
});
Comments:
change:
//html
@Html.CheckBoxFor(model => model.Permitir, new { id = "toggle1"
//javascript
$('#toggle1').bootstrapToggle();
that's why:
//html
@Html.CheckBoxFor(model => model.Permitir, new { id = "Permitir"
//javascript
$('input[type='checkbox'][name='Permitir']').bootstrapToggle();
this is important in validating, standardizing, and maintaining your code.