Validate select with jQuery Validator

Asked

Viewed 623 times

2

I got a select like that:

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

I leave that select enabled to select more than one option with the multiselect.js thus:

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

I try to validate if at least one select option was selected with 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 if I do not select anything in select, the form is submitted, it is not validated.

1 answer

1

You only have a small error in your script, the correct 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>
<script src="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>

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

  • The code you posted here works perfectly, but here in my environment does not work, I must have some more syntax error in my code. + 1 for you.

  • See if there is an error in the @Leandrolima browser console. Maybe the library hasn’t been loaded yet..

  • I have seen, there is no mistake. Another bizarre thing I noticed is that if I put ().multiSelect doesn’t work properly, now if I put ().multiselect works. I think someone tampered with the plugin core after importing to the project ): Thanks @Lucas Costa

  • 1

    Or problem with version. Try to put the same version of the documentation as I did in the example. And see if the version is compatible with the version of jQuery, if using jQuery 3 can happen problems too.

Browser other questions tagged

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