1

I have the following bootstrap drop-down menu:

<div class="form-group">
    <label for="name" class="col-md-3 control-label">Pens</label>
    <div class="col-md-9">
        <div class="btn-group btn-input">
            <button id="pensList"  type="button"
                class="btn btn-default dropdown-toggle form-control"
                data-toggle="dropdown">
                <span data-bind="label">Nothing selected</span> 
                <span class="caret"></span>
            </button>
            <ul id="elements" class="dropdown-menu">
              <li id="my_li_id_0"><a href="#">Nothing selected</a></li>
              <li id="my_li_id_1"><a href="#">Ballpoint Pens</a></li>
              <li id="my_li_id_2"><a href="#">Rollerball Pens</a></li>
              <li id="my_li_id_3"><a href="#">Fountain Pens</a></li>
              <li id="my_li_id_4"><a href="#">Custom pens</a></li>
            </ul>
        </div>
    </div>
</div>

And this script for making it drop down:

$(document.body).on('click', '.dropdown-menu li',
function(event) {
     var $target = $(event.currentTarget);

     $target.closest('.btn-group').find(
        '[data-bind="label"]').text( 
            $target.text()).end().children('.dropdown-toggle').dropdown('toggle');

        return false;
});

How can I apply jquery validation on it, raising error on the element with id my_li_id_0?

GingerHead
  • 7,882
  • 14
  • 54
  • 91
  • 1
    The jQuery Validate plugin only validates standard data input elements... ``, ` – Sparky Jun 01 '14 at 01:49

1 Answers1

8

The jQuery Validate plugin can only validate input, textarea, and select elements contained within a form container. It cannot validate an unordered list. ( EDIT: In newer versions, it can also validate certain kinds of elements with a contenteditable attribute. )

You'll have to construct a workaround. Something like this...

  1. Bind an event to the Bootstrap drop-down menu that's fired whenever the user makes or changes a selection.

  2. Whenever that event from #1 is fired, copy the desired value from the list into a hidden input element.

  3. Set the plugin's ignore option to [] so nothing is ignored and hidden input elements are validated.

  4. Set your validation rules on the name of the hidden input element.

  5. Use the .valid() method within your function on #2 above to trigger a validation test on the hidden input element whenever the selection is changed.

  6. Use a conditional within the plugin's errorPlacement callback function to put the validation message in a location more relevant to the Bootstrap pulldown menu. You'll need a conditional in order to preserve the default error placement code for the other elements.


BTW: Your numerical id...

<li id="1">

...might be technically correct in HTML5, however, an id starting with a number could be a problem in other areas. More info: What are valid values for the id attribute in HTML?

Sparky
  • 94,381
  • 25
  • 183
  • 265