使用jQuery验证为div设置验证 [英] Set validation for div using jQuery validation

查看:96
本文介绍了使用jQuery验证为div设置验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery validation plugin 进行表单验证.但是,我无法为 div 设置验证.

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方法:

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

我以前没有做过,请提供您的建议.

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

推荐答案

引用OP:

"我正在使用jQuery Validation插件进行表单验证....但是,我无法为div设置验证.我以前没有这样做,请提供您的建议. "

"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."

您将永远无法使用jQuery Validate插件来验证div.用于数据输入的正确HTML标记是使用输入元素.

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.

此插件仅适用于以下类型的数据输入元素(每个必须具有唯一的name属性),并且这些必须 >元素容器:

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>

另请参阅文档中的参考"页面: http://jqueryvalidation.org/reference/

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

显然,OP无法更改HTML.这是一个非常丑陋的解决方法.

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

可用于将div的文本复制到type="hidden"元素中的代码,然后可以使用插件验证隐藏的元素.可以随时调用此代码,也可以将其放在事件处理程序中以在模糊或更改时触发:

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() );

以下是对应的jQuery:

Here is the corresponding jQuery:

$('#form').validate({
    ignore: [], // <-- validate hidden elements
    // other options, rules, and callbacks,
});

这篇关于使用jQuery验证为div设置验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆