Validate Jquery does not work with Toggle Bootstrap

Asked

Viewed 487 times

3

I’m using http://www.bootstraptoggle.com/, 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 look true. Validate is not working. Any solution ?

1 answer

2


When using Bootstrap Toggle has a problem: messages do not appear (that plugin adds a div that obfuscates the validation message) by not getting a response from validated or nay, but has a friendly way of showing all the mistakes with errorLabelContainer, minimal 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"
});

Online Example

Remarks:

change:

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

therefore:

//html
@Html.CheckBoxFor(model => model.Permitir, new { id = "Permitir"
//javascript
$('input[type='checkbox'][name='Permitir']').bootstrapToggle();

this is important in the validation, standardization and maintenance of your code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.