标签:插件 ges styles nal sub ror static rap nbsp
1、引入bootstrap和validate
<script src="{% static ‘js/jquery.min.js‘ %}"></script> <link href="{% static ‘css/bootstrap.css‘ %}" rel="stylesheet"> {# 前端校验validate #} <script src="{% static ‘js/jquery.validate-1.14.0.js‘ %}"></script> <script src="{% static ‘js/jquery-validation-1.14.0-localization-messages_zh.js‘ %}"></script>
2、修改bootstrap.css文件,增加如下样式描述,主要是给表单前增加红色星号*,和必填提示样式
/*必填项前加红色星号*/ .form-group.required .control-label:before { color: red; content: "*"; position: absolute; margin-left: -15px; } /************jQuery.Validate插件样式开始********************/ label.error { color: Red; padding-left: 0px; } input.error { border: dashed 1px red; } select.error { border: dashed 1px red; } textarea.error { border: dashed 1px red; }
3、给表单加上required属性
{# 新增模态框body #} <form id="add-project"> <div class="modal-body" style="height: 100%;"> {# 给class属性增加 required #} <div class="form-group required"> <label for="firstname" class="col-sm-3 control-label">IP</label> <div class="col-sm-7"> {# 增加 required 属性,也可以在下方规则出添加 #} <input type="text" class="form-control" id="server_ip" name="server_ip" required placeholder="请输入ip"> </div> </div> <div class="form-group required"> <label for="firstname" class="col-sm-3 control-label">子系统名称</label> <div class="col-sm-7"> <select data-placeholder="选择子系统..." class="form-control" name="sub_sys" id="sub_sys" required="required"> </select> </div> </div> </div> </form>
4、编写form表单必填项校验规则
<script type="text/javascript"> {# 对id="add-project"的表单设置校验规则 #} $("#add-project").validate({ {# 校验规则 #} rules: { {# 给name属性为server_ip的标签设置规则 #} server_ip: { required: true, // 设为必填项 {# 正则表达式校验ip格式 #} ip_validate: true // 增加实时输入校验 }, sub_sys: { required: true, digits: true }, }, messages: { server_ip: "请输入合法的IP", sub_sys: "请输入正整数" }, submitHandler: function (form) { $(form).ajaxSubmit(); }, }); {# 增加自定义的ip校验 #} $.validator.addMethod("ip_validate", function (value, element) { let ip_validate = /^((\d)|([1-9]\d)|(1\d{2})|((2[0-4]\d)|(25[0-5])))(\.((\d)|([1-9]\d)|(1\d{2})|((2[0-4]\d)|(25[0-5])))){3}$/; return this.optional(element) || (ip_validate.test(value)); }, "请输入合法的IP"); </script>
5、提交表单前校验,校验不通过不请求接口
function add_project() { // 先校验表单在前端是否校验通过 let flag = $("#add-project").valid(); if (!flag) { //没有通过验证,就不进行下面的ajax提交了 return; } {#ajax请求接口#} $.ajax({ }) }
6、提示效果
直接提交时提示如下:
输入不合法数据时提示:
标签:插件 ges styles nal sub ror static rap nbsp
原文地址:https://www.cnblogs.com/gcgc/p/14846072.html