最简单的JQuery验证规则示例

Geo*_*pty 16 javascript validation jquery declarative

以下HTML表单成功使用了jQuery的表单验证,如果留空,则在表单字段右侧显示"此字段是必需的",如果输入的字符少于2个,则"请输入至少2个字符".但是,我不想使用"cname"表单输入字段中的class和minlength属性指定验证元数据,而是使用jQuery的"规则"API,其中规则在validate函数的主体中指定.提前致谢:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="/lib/js/jquery.js"></script>
  <script src="/lib/js/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){$("#commentForm").validate(
    /*
     rules/messages here
    */
    );}
    );
  </script>
</head>
<body>

 <form id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Ayo*_*Ayo 14

rules: {
    cname: {
        required: true,
        minlength: 2
    }
},
messages: {
    cname: {
        required: "<li>Please enter a name.</li>",
        minlength: "<li>Your name is not long enough.</li>"
    }
}
Run Code Online (Sandbox Code Playgroud)


Geo*_*pty 12

此博客文章中包含的示例可以解决问题.

  • 我是积极主动并添加链接的情况下,存档,web.archive.org文章原文链接永远不会消逝:http://web.archive.org/web/20120108075037/http://www.raymondcamden的.com/index.cfm/2009/2/10 /安介绍到jQuery的和表格验证-2- (2认同)
  • 您应该只清除此链接的答案. (2认同)