Validate when value is "Selected" DropdownList with JQuery.Validity

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 problems with DropDownList , because the same default has the Selected value. Would you like to adjust for Selected to perform validation?

    
asked by anonymous 13.03.2018 / 19:45

1 answer

0

Create a method to check the value of the option content chosen, in the case of this example, the drop1 field has a option with the value ="" so in the function this value was checked:

$.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><scriptsrc="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><scriptsrc="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>
    
13.03.2018 / 22:46