Set validation for div using jQuery validation

妖精的绣舞 提交于 2020-01-21 03:37:08

问题


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.


回答1:


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,
});



回答2:


I'm not sure why are you trying to validate a div but I suggest making it a textarea. In case you need to make it 'impossible' for the user to edit, add the readonly attribute.

<form id="form">
  <textarea id="location" name="location" readonly></textarea>
</form>


来源:https://stackoverflow.com/questions/19030206/set-validation-for-div-using-jquery-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!