Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set validation for div using jQuery validation

I'm using jQuery validation plugin, for my form validation. However I'm unable to set the validation for a div.

Here is what I have tried so far

HTML:

<form id="form">
  <div id="location" name="location"></div>
</form>

JS:

$('#form').validate({
            rules: {
            isLocationEmpty: true;
            }
});

CustomValidation Mehthod:

$.validator.addMethod('isLocationEmpty', function (value, element) {        
    var loc = $('#location').text();
    return (loc != "")
}, 'REQUIRED.');

I'm haven't done this previously, please provide your suggestions.

like image 930
Praveen Avatar asked Sep 26 '13 13:09

Praveen


1 Answers

Quote OP:

"I'm using jQuery Validation plugin for my form validation.... However I'm unable to set the validation for a div. I haven't done this previously, please provide your suggestions."

You will never be able to use the jQuery Validate plugin to validate a div. The proper HTML markup for data input is to use an input element.

This plugin will only work on the following kinds of data input elements (each must have a unique name attribute), which also must be within a form element container:

<form>

   <!-- // Input - Also including the various HTML5 input types
   // type = text, password, radio, checkbox, file, etc. -->
   <input type="text" name="something" />

   <!-- Hidden Input - 'ignore: []' must be defined in the options -->
   <input type="hidden" name="hide" />

   <!-- Select Dropdown -->
   <select name="foobar"> ... </select>

   <!-- Text Area Box -->
   <textarea name="barfoo"></textarea>

</form>

Also see the "reference" page in the docs: http://jqueryvalidation.org/reference/


Apparently the OP cannot change the HTML. Here is a very ugly workaround.

Code that can be used to copy the text of the div into a type="hidden" element, where the hidden element can then be validated with the plugin. This code can be called at any time or placed inside an event handler to fire upon blur or change:

$("#hidden").val( $('#div').text() );

Here is the corresponding jQuery:

$('#form').validate({
    ignore: [], // <-- validate hidden elements
    // other options, rules, and callbacks,
});
like image 120
Sparky Avatar answered Nov 07 '22 06:11

Sparky