简单教程
提交运行
代码编辑器:
<!doctype html> <meta charset="utf-8"/><style>html,body{height:100%}</style> <!DOCTYPE html> <meta charset="utf-8"> <link href="/static/next/css/tryit.css?v=2017082407" rel="stylesheet"/> <style> .error{ color:red; } fieldset {border:1px solid #ddd;} </style> <p>将错误信息放在 label 元素后并使用 span 元素包裹它</p> <form method="get" class="cmxform" id="form1" action=""> <fieldset> <legend>Login Form</legend> <p> <label for="user">Username</label> <input id="user" name="user" required minlength="3"> </p> <p> <label for="password">Password</label> <input id="password" type="password" maxlength="12" name="password" required minlength="5"> </p> <p> <input class="submit" type="submit" value="Login"> </p> </fieldset> </form> <footer>简单教程,简单编程<br/>Copyright © 简单教程 www.twle.cn</footer> <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { // 提交时验证表单 var validator = $("#form1").validate({ errorPlacement: function(error, element) { // Append error within linked label $( element ) .closest( "form" ) .find( "label[for='" + element.attr( "id" ) + "']" ) .append( error ); }, errorElement: "span", messages: { user: { required: " (必需字段)", minlength: " (不能少于 3 个字母)" }, password: { required: " (必需字段)", minlength: " (字母不能少于 5 个且不能大于 12 个)", maxlength: " (字母不能少于 5 个且不能大于 12 个)" } } }); $(".cancel").click(function() { validator.resetForm(); }); }); </script>
运行结果: