页面引入jquery.validate.min.js
<style> //引入错误格式
label.error {
display: block;
margin-left: 1em;
auto;
color: red;
}
</style><script type="text/javascript" src="/library/js/jquery.validate.min.js"></script>
要验证的form,必须是form表单,提交不提交的无所谓
<form target="hiddenIframe" id="content"> <div class="modal-body" style="margin-left:110px;"> <label style="float:left" for="fieldType">①字段类型<span style="color:red">*</span>:</label> <input style="float:left;margin-left:40px;" type="text" name="fieldType" id="fieldType"/> <br> <br> <label style="float:left" for="intro">②字段名称<span style="color:red">*</span>:</label> <input style="float:left;margin-left:39px;" type="text" name="fieldName" id="fieldName"/> <br/> <br/> <label style="float:left" for="orderNumber">③排序(数字):</label> <input style="float:left;margin-left:6px;" type="text" name="orderNumber" id="orderNumber"/> <br/> <br/> <label style="float:left" for="isDisable">④使用情况:</label> <input type="radio" name="isDisable" value="0"/>禁用 <input type="radio" name="isDisable" value="1" checked/>启用 <br/> <br/> <label style="float:left" for="remark">⑤备注:</label><br> <textarea rows="6" cols="40" name="remark" id="remark"></textarea> <br> <br> <div class="error">error:</div> //--------错误显示地方 </div> <div class="modal-footer"> <input id="insertField" type="button" style="margin-left: 150px;margin-top: 20px;" value="新增数据字典" class="btn btn-primary"></a> <input type="button" style="margin-left: 150px;margin-top: 20px;" value="取消" class="btn btn-primary" data-dismiss="modal" onclick="javascript:window.location.reload();"></a> <iframe name="hiddenIframe" id="hiddenIframe" style="display:none"></iframe> </div> </form>
js中如下:
//验证方法 function valContent(){ return $("#content").validate({ errorLabelContainer: $("#content div.error"), rules: { fieldName: { //fieldName 是页面的name属性 required: true }, orderNumber:{ number: true, digits: true, min :0 } }, messages: { fieldName: { required: "请填写字段名称" }, orderNumber:{ number: "请输入合法的排序数字", digits: "排序只能输入整数", min :$.validator.format("不能小于0") } } }).form(); }
发送的ajax请求如下:
//新增数据字典 $("#insertField").click(function(){ var fieldType = $("#fieldType").val(); var fieldName = $("#fieldName").val(); var orderNumber = $("#orderNumber").val(); var isDisable = $("input[type='radio']:checked").val(); var remark = $("#remark").val();
if(valContent()){ $.post(ctx+"/field/insert",{fieldType:fieldType,fieldName:fieldName,orderNumber:orderNumber,isDisable:isDisable,remark:remark},function(msg){ if(msg.success){ $("#myModal").modal('toggle'); loadSignIn(); } }); } });