Validate select with jQuery Validator

2

I have a select like this:

<form action="" id="form">
    <select name="unidadeNegocio[]" id="unidadeNegocio" multiple="multiple" >
        <option> A </option>
        <option> B </option>
        <option> C </option>
    </select>
</form>

I allow this select enabled to select more than one option with multiselect.js like this:

$(document).ready(function(){
    $('#unidadeNegocio').multiselect();
});

I try to validate if at least one select option was selected with the Validate (plugin to validate inputs) like this:

$('#form').validate({
  rules: {
    "unidadeNegocio[]": {
      required: true,
      minlength: 1
    },
    messages: {
      "unidadeNegocio[]": {
        required: 'Por favor, selecione pelo menos um'
      }
    }
  }
})

The problem is that even though I do not select anything in the select, the form is submitted, it is not validated.

    
asked by anonymous 25.10.2017 / 15:05

1 answer

1

You only have one small error in your script, the correct one is multiSelect and not multiselect .

$(function() { 
  $('#unidadeNegocio').multiSelect();
});

$('#form').validate({
  rules: {
    "unidadeNegocio[]": {
      required: true,
      minlength: 1
    },
    messages: {
      "unidadeNegocio[]": {
        required: 'Por favor, selecione pelo menos um'
      }
    }
  }
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/css/multi-select.css" media="screen" rel="stylesheet" type="text/css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/multi-select/0.9.12/js/jquery.multi-select.min.js"></script><formaction="" id="form">
  <select name="unidadeNegocio[]" id="unidadeNegocio" multiple="multiple">
        <option> A </option>
        <option> B </option>
        <option> C </option>
    </select>
  <input type="submit">
</form>
    
25.10.2017 / 15:23