jQuery验证插件。验证非表单字段?

时间:2011-11-06 15:15:46

标签: javascript jquery validation

Ні,all!

我对jQuery.Validation插件有一个小问题: - 我可以使用jQuery.Validation插件完成非表单字段输入字段的验证(即“form”标记中的否)吗?

感谢。

1 个答案:

答案 0 :(得分:1)

是的,你可以,但该字段仍然需要在一组<form>标签内。但是,您需要“提交”此form以检查内部字段的验证。您可以使用.valid()方法独立于form提交来检查此表单。

http://jsfiddle.net/9fgVN/13/

<form id="myNonsubmitForm" action="#">
    <textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>

<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />

$(document).ready(function() {

    $("#myNonsubmitForm").validate({
        validClass: 'valid',  // as per your configuration
        rules: {  // set rules as per your configuration
            comments: {
                required: false,
                maxlength: 10
            }
        },
        errorPlacement: function(error, element) {
             // use this to control placement of error messages
             // removal of errorPlacement handler will result in message appearing next to field automatically.
        }
    });

    $("#myButton").click(function() { // validate on button click for this example
        if($("#myNonsubmitForm").valid()){
            $('#output').val('passed');
        } else {
            $('#output').val('failed');
        };
    });

});