jQuery 使用类属性进行验证

jquery validation using class attribute

本文关键字:验证 属性 jQuery      更新时间:2023-09-26

我的表单中有多个文本字段,其中应仅包含 5 个字母和必填字段。我正在使用类属性对此使用jQuery验证。

示例代码:

<html>
    <head>
        <title>Title</title>
    </head>
    <cfsavecontent variable="headerJS">
        <script type="text/javascript" src="js/validateCurrency.js"></script> 
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> 
        <script type="text/javascript" src="js/jquery.validate.min.js"></script>
        <script>
            $(function() {
                alert("function");
                jQuery.validator.addMethod("APUnit", function(value, element) {
                    return this.optional(element) || /^[A_Za-z]{5}$/i.test(value);
                }, " ");
                jQuery.validator.addMethod("cRequired", jQuery.validator.methods.required, "Customer name required");       
                jQuery.validator.addClassRules("APunit1",{APUnit: true, cRequired: true});          
            }); 
        </script>
        <style>
            label.error {
                color: red;
                font-style: italic;
                background: transparent url(images/unchecked.gif) no-repeat scroll 0 0;
                padding-left:20px;
                margin-left:10px;
            }
            input.error { border: 1px dotted red; }
            .border td {
                border-left: 1px solid black;
                border-right: 1px solid black;
                border-top: 1px solid black;
                border-bottom: 1px solid black;
            }
            .border th{
                border-left: 1px solid black;
                border-right: 1px solid black;
                border-top: 1px solid black;
                border-bottom: 1px solid black;
            }
        </style>
    </cfsavecontent>
    <cfhtmlhead text="#headerJS#">
    <body>
        <cfform name="eForm" method="POST">
            Name: <input type="text" name="name" class="APUnit1">
            <input type="submit" value="Submit">
        </cfform>
    </body>
</html>

但是当我输入无效时,我没有收到任何错误消息。验证正在工作。我找不到其中的错误。请帮助我度过难关。

无论您如何创建和/或声明规则,您仍然必须将 .validate() 方法附加到表单中才能初始化插件。

$(function() {
    $('form[name="eForm"]').validate();
    jQuery.validator.addMethod("APUnit", function(value, element) { ....
    ....

你在这里也拼错了APunit1...

<input type="text" name="name" class="APUnit1">

这里拼写为APunit1...

jQuery.validator.addClassRules("APunit1" ....

初始化插件并修复拼写错误:

工作演示:http://jsfiddle.net/pcgb4moj/