Validate Jquery does not work with Bootstrap Toggle

3

I'm using link , a simple toggle of true or false.

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 required. It needs to stay true. Validate is not working. Any solution?

    
asked by anonymous 12.01.2017 / 00:20

1 answer

2

When you use Bootstrap Toggle have a problem: Messages do not appear ( this plugin adds a div that obfuscates the validation message) getting the response from validated or not , but has a friendly way to show all errors with errorLabelContainer , minimum example:

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"
});

Example Online

switch:

//html
@Html.CheckBoxFor(model => model.Permitir, new { id = "toggle1"
//javascript
$('#toggle1').bootstrapToggle();

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.

    
12.01.2017 / 00:45