Validate when the value is "Selected" Dropdownlist with Jquery.Validity

Asked

Viewed 167 times

0

I have the following code jQuery:

$("#aspnetForm").validate({
    errorElement: 'span',
    errorClass: 'help-block',
    rules: {
        Dropdown: {
            required: true
        }
    },
    messages: {
        Dropdown: {
            required: "Preencha o campo"
        }
    },
    highlight: function (element) { 
        $(element)
            .closest('.form-group').removeClass('has-success').addClass('has-error'); 
    },
    unhighlight: function (element) { 
        $(element)
            .closest('.form-group').removeClass('has-error'); 
    }
});

this same code works with my TextBox, but I’m having trouble with DropDownList, yeah, the same by default has the value Selected. It would have to adapt for while is marked the Selected he perform the validation?

  • The code worked for you?

1 answer

0

Create a method to verify the value of the option chosen, in the case of this example, the field drop1 has a option with the value ="" then in the function was verified that value:

$.validator.addMethod("selectrequired", function(value, element, arg) {
  return arg != element.value;
}, 'Select');

$("#form1").validate({
  errorElement: 'span',
  errorClass: 'help-block',
  rules: {
    nome: {
      required: true
    },
    drop1: {
      selectrequired:""
    }
  },
  messages: {
    nome: {
      required: "Preencha o campo"
    },
    drop1: {
      selectrequired: "Escolha o item"
    }
  },
  highlight: function(element) {
    $(element)
      .closest('.form-group').removeClass('has-success').addClass('has-error');
  },
  unhighlight: function(element) {
    $(element)
      .closest('.form-group').removeClass('has-error');
  }
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/localization/messages_pt_BR.min.js"></script>

<form id="form1" class="form">
  <label for="nome">Nome</label>
  <input type="text" name="nome" id="nome" class="form-control" />
  <label for="nome">Nome</label>
  <select id="drop1" name="drop1" class="form-control">
    <option value="">Selecione</option>
    <option value="S">Sim</option>
    <option value="N">Não</option>
  </select>
  <br>
  <button class="btn btn-success">Enviar</button>
</form>

Browser other questions tagged

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