bootstrap-validation.js表单验证

孔俊爽
2023-12-01

<link href="/gdcsg-root/resources/js/metronic/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="/gdcsg-root/resources/js/metronic/global/plugins/bootstrap-validation/bootstrap-validation.js"></script>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.gdcsg.com/toJson" prefix="el" %>
<%@ taglib uri="http://www.gdcsg.com/toJson" prefix="el" %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增</title>
<style type="text/css">
   #testInInfoForm .row
   {
      margin-top: 5px;
   }
   .required{
      color:red;
   }
</style>
</head>
<body>
<form:form id="testInTaskForm" method="post" modelAttribute="testInTask">
   <form:hidden path="taskId"/>
   <form:hidden path="type"/>
   <form:hidden path="testInfo"/>
   <div class="row form-group margin-10">
      <div class="col-md-2"></div>
      <label class="col-md-2 control-label">周期<font
            class="required">*</font>:</label>
      <div class="col-md-6 controls">
         <form:select id="jobId" path="jobId" cssClass="form-control"
                   check-type="required" required-message="周期不能为空">
            <form:option value="">请选择</form:option>
            <c:forEach var="item" items="${joblist}">
               <form:option value="${item.jobId}">${item.jobName}</form:option>
            </c:forEach>
         </form:select>
      </div>
      <div class="col-md-2"></div>
   </div>
</form:form>
<form id="UDPForm">
   <div class="row form-group margin-10">
      <div class="col-md-2"></div>
      <label class="col-md-2 control-label">目标IP<font
            class="required">*</font>:</label>
      <div class="col-md-6 controls">
         <input name="ip" type="text" class="form-control" check-type="required checkIp" 
               required-message="ip不能为空" value="<c:if test="${!empty testInTask.testInfo}" >${el:toJson(testInTask.testInfo).ip}</c:if>"/>
      </div>
      <div class="col-md-2"></div>
   </div>
   <div class="row form-group margin-10">
      <div class="col-md-2"></div>
      <label class="col-md-2 control-label">端口<font
            class="required">*</font>:</label>
      <div class="col-md-6 controls">
         <input name="prot" type="text" class="form-control" check-type="required checkPortName ajaxCheck" 
               ajaxFunction="checkZPtpName" ajaxCheck-message="端口号已被使用!"  required-message="端口不能为空" 
               value="<c:if test="${!empty testInTask.testInfo}" >${el:toJson(testInTask.testInfo).prot}</c:if>"/>
      </div>
      <div class="col-md-2"></div>
   </div>
</form>
<script type="text/javascript">
   function checkZPtpName() {
      
    }
</script>
</body>
</html>
bootstrap-validation.js默认的方法有如下:

$.fn.validation.defaults = {
      validRules : [
          {name: 'required', validate: function(value) {return ($.trim(value) == '');}, defaultMsg: '请输入内容。'},
          {name: 'maxLength', validate: function(value) {
              return (value.replace(/[^\u0000-\u00ff]/g,"00").length > this.attributes['max-length'].value);
          }, defaultMsg: '文本长度超出指定长度!'},
          {name: 'number', validate: function(value) {if(value!="") return (!/^[0-9]\d*$/.test(value));}, defaultMsg: '请输入数字。'},
          {name: 'monthDay', validate: function(value) {if(value!="") return (!/^((0[1-9]|[1-2][0-9])|([3][0-1]))$/.test(value));}, defaultMsg: '请输入一个月中的某一天'},
          {name: 'HHmm', validate: function(value) {if(value!="") return (!/^(([01]?[0-9]|2[0-3]):[0-5][0-9])$/.test(value));}, defaultMsg: '请输入一天中的不精确到秒的某个时间'},
          {name: 'mail', validate: function(value) {if(value!="") return (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}$/.test(value));}, defaultMsg: '请输入合法的邮箱地址,必须含有@'},
          {name: 'multiMail', validate: function(value) {if(value!="") return (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}(,[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3})*$/.test(value));}, defaultMsg: '请输入邮箱地址。多个邮箱地址时用","(英文逗号)隔开'},
          {name: 'char', validate: function(value) {if(value!="") return (!/^[a-z\_\-A-Z]*$/.test(value));}, defaultMsg: '请输入英文字符。'},
          {name: 'chinese', validate: function(value) {if(value!="") return (!/^[\u4e00-\u9fff]$/.test(value));}, defaultMsg: '请输入汉字。'},
          {name: 'noChinese', validate: function(value) {if(value!="") return (/[\u4e00-\u9fa5]/.test(value));}, defaultMsg: '不能含有汉字。'},
          {name: 'ajaxCheck', validate: function(value) {
                    //调用ajaxFunction属性设置的函数名
                    return window[this.attributes['ajaxFunction'].value](value, this);
                 }, defaultMsg: '请输入内容。'
              },
          
          {name: 'checkConfirm', validate: function(value) {return checkConfirm(value);}, defaultMsg: '确认密码不能为空!'},
          {name: 'checkPassword', validate: function(value) {return checkPassword(value);}, defaultMsg: '密码不一致!'},
          {name: 'checkTime', validate: function(value) { var sysTime = new Date();
                                            var expired_Date = new Date(value);
                                            return sysTime.getTime() > expired_Date.getTime();}, defaultMsg: '过期时间不能小于当前时间!'},
          /*(修改)密码验证*/
          {name: 'checkPasswordFormatUpdatePw1', validate: function(value) {return checkPasswordFormatUpdatePw1();}, defaultMsg: '密码少于十位!'},
          {name: 'checkPasswordFormatUpdatePw2', validate: function(value) {return checkPasswordFormatUpdatePw2();}, defaultMsg: '密码不满足  [数字+符号+大小写字母 ] 的组合!'},
          {name: 'checkPasswordFormatUpdatePw3', validate: function(value) {return checkPasswordFormatUpdatePw3();}, defaultMsg: '密码不能与最近5次使用过的密码相同!'},
          /*(新增或者修改用户)密码验证*/
          {name: 'checkPasswordFormatUpdateUser1', validate: function(value) {return checkPasswordFormatUpdateUser1();}, defaultMsg: '密码少于十位!'},
          {name: 'checkPasswordFormatUpdateUser2', validate: function(value) {return checkPasswordFormatUpdateUser2();}, defaultMsg: '密码不满足  [数字+符号+大小写字母 ] 的组合!'},
          {name: 'checkPasswordFormatUpdateUser3', validate: function(value) {return checkPasswordFormatUpdateUser3();}, defaultMsg: '密码不能与最近5次使用过的密码相同!'},
          /*zlk: 结束IP地址段*/
          {name: 'checkEndIp', validate: function(value) {return checkEndIp();}, defaultMsg: '结束地址段范围不能小于开始地址段,并且前两个地址段必须相同'},
          
          {name: 'checkNew', validate: function(value) {return checkNew(value);}, defaultMsg: '与原密码不一致!'},
          {name: 'officePhone', validate: function(value) {if(value!="")return (!/^(\d{3,4}-)?\d{7,8}$/.test(value));}, defaultMsg: '电话号码格式不对!'},
          {name: 'mobilePhone', validate: function(value) {if(value!="")return (!/^1[35][0-9]{9}$/.test(value));}, defaultMsg: '手机号码格式不对!'},
          {name: 'checkVEthName', validate: function(value) {return checkVEthName(value);}, defaultMsg: '虚拟端口格式不合法!'},
          {name: 'checkZero', validate: function(value) {return (/^[0]/.test(value));}, defaultMsg: '不能以数字0开头!'},
          {name: 'checkIp', validate: function(value) {
              if(value == ""){
                 return false;
              }
              return (!/^((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){3}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/.test(value));
           }, defaultMsg: 'ip地址不合法!'},
          {name: 'checkCollector', validate: function(value) {return checkCollector(value); }, defaultMsg: '已存在相同的采集机编号与类型,请更改其它的编号或者类型!'},
          {name: 'checkLoginName', validate: function(value) {return checkLoginName(value); }, defaultMsg: '已存在相同的用户登陆名,请更改其他用户登陆名!'},
          {name: 'checkModelId', validate: function(value) {return checkModelId(value);}, defaultMsg: '网元型号已经存在!'},
          {name: 'checkPtpName', validate: function(value) {
           var reg1 = new RegExp("^([0-9]+/){0,3}[0-9]+$");
           var reg2 = new RegExp("Eth-Trunk[0-9]\d{0,2}$");
           var reg3 = new RegExp("smartgroup[0-9]\d{0,2}$");
           return !(reg1.test(value) || reg2.test(value) || reg3.test(value));
       }, defaultMsg: '端口号不合法!'},
       {name: 'checkPtpNameByAuto', validate: function(value) {
           if(value=="N/A"){
              return false;
           }
           var reg1 = new RegExp("^([0-9]+/){1,3}[0-9]+$");
           var reg2 = new RegExp("Eth-Trunk[0-9]\d{0,2}$");
           var reg3 = new RegExp("smartgroup[0-9]\d{0,2}$");
           return !(reg1.test(value) || reg2.test(value) || reg3.test(value));
       }, defaultMsg: '端口号不合法!'},
          {name: 'checkCard', validate: function(value) {
               var reg = new RegExp("^([0-9]+/){1,2}[0-9]+$");
               return !(reg.test(value));
           }, defaultMsg: '板卡不合法!'},
          {name: 'checkPtpNameNullable', validate: function(value) {
              if(value.length>0) {
                  var reg1 = new RegExp("^([0-9]+/){1,3}[0-9]+$");
                  var reg2 = new RegExp("Eth-Trunk[0-9]\d{0,2}$");
                  var reg3 = new RegExp("smartgroup[0-9]\d{0,2}$");
                  return !(reg1.test(value) || reg2.test(value) || reg3.test(value));
              }
          }, defaultMsg: '端口号不合法!'},
          {name: 'checkPtpNameNullable1', validate: function(value) {
              if(value.length>0) {
                  var reg1 = new RegExp("^([0-9]+/){1,3}[0-9]+$");
                  var reg2 = new RegExp("\\[(([0-9]+/){1,3}[0-9]+,?){2}\\]-\\d{1,3}");
                  return !(reg1.test(value) || reg2.test(value));
              }
          }, defaultMsg: '端口号不合法!'},
          {name: 'checkMultipleIp', validate: function(value) {return (!/^(([1-9]|[1-9]\d|1\d{2}|2[0-1]\d|22[0-3])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3},?)+$/.test(value));}, defaultMsg: 'ip地址不合法!'},
          {name: 'checkIp2', validate: function(value) {return (!/^([1-9]|[1-9]\d|1\d{2}|2[0-1]\d|22[0-3])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){3}$/.test(value));}, defaultMsg: 'ip地址不合法!'},
          {name: 'checkPrivateIp', validate: function(value) {
             /*  //A类网络地址,广播地址
              if(/^([1-9]|[1-9]\d|1[0-1]\d|12[0-6])((\.0){3}|(\.1){3})$/.test(value)){
                  return true;
              }
              //B类网络地址,广播地址
              if(/^(12[8-9]|1[3-8]\d|19[0-1])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])((\.0){2}|(\.1){2})$/.test(value)){
                  return true;
              }
              //C类网络地址,广播地址
              if(/^(19[2-9]|2[0-1]\d|22[0-3])(\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){2}\.[0-1]$/.test(value)){
                  return true;
              }*/
              //A类私有地址
              if(/^(10|127)\.((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){2}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/.test(value)){
                  return true;
              }
              //B类私有地址
              else if(/^(172\.16\.)((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){1}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/.test(value)){
                  return true;
              }
              //C类私有地址
              else if(/^(192\.168\.)((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){1}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/.test(value)){
                  return true;
              }
              return false;
          }, defaultMsg: '不能使用IP私有地址!'},
          {name: 'checkIpSegment', validate: function(value) { return  checkIpSegment(value); }, defaultMsg: '结束地址段范围不能小于开始地址段!'},
          {name: 'checkVeName', validate: function(value) {var reg = new RegExp("[a-zA-Z0-9]*([0-9]+/){0,3}[0-9]+$");return !reg.test(value);}, defaultMsg: '虚拟端口格式不合法!'},
          {name: 'checkMask', validate: function(value) {
           var flag = false;
           if(/^((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){3}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/.test(value)){
              var maskArray = ["128.0.0.0", "192.0.0.0", "224.0.0.0", "240.0.0.0", "248.0.0.0", "252.0.0.0", "254.0.0.0",
                              "255.0.0.0", "255.128.0.0", "255.192.0.0", "255.224.0.0", "255.240.0.0", "255.248.0.0", "255.252.0.0",
                              "255.254.0.0", "255.255.0.0", "255.255.128.0", "255.255.192.0", "255.255.224.0", "255.255.240.0",
                              "255.255.248.0", "255.255.252.0", "255.255.254.0", "255.255.255.0", "255.255.255.128", "255.255.255.192",
                              "255.255.255.224", "255.255.255.240", "255.255.255.248", "255.255.255.252", "255.255.255.254", "255.255.255.255"];
              for(var i=0;i<maskArray.length;i++){
                 if(maskArray[i] == value){
                    flag = true;
                    break;
                 }
              }
           }
         if(flag == false){
            flag = /^([1-9]|[1-2]\d|3[0-2])$/.test(value);
         }
         return !flag;}, defaultMsg: '掩码不合法'
      },
      {name: "checkSpace", validate: function(value){
         var idx = value.indexOf(" ");
         if(idx == -1){
            return false;
         }else{
            return true;
         }
      }, defaultMsg: '内容不能包含空格!'},
      {name: "checkLoginName", validate: function(value){
         debugger
         var spiReg = new RegExp("[?!@#$%\\^&*()'\"<>+]+");
         var sqlReg = new RegExp("(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"  
                  + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)");
         if(spiReg.test(value) || sqlReg.test(value)){
            return true;
         }else{
            return false;
         }                  
      }, defaultMsg: '登录账号含非法字符!'},
      {name: 'checkPortName', validate: function(value) {
           var reg1 = new RegExp("^([0-9]+/){0,3}[0-9]+$");
           return !reg1.test(value);
       }, defaultMsg: '端口号不合法!'},
          {name: 'CheckAuthority', validate: function(value) {
      //调用ajaxFunction属性设置的函数名
      return window[this.attributes['CheckAuthorityFunction'].value](value, this);
   }, defaultMsg: '请输入内容。'
},        
      ]
  };

调用示例如下:

//form表单转json字符串
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$("#testInTaskSaveBtn").click(function () {
    if($("#type").val()!="HTTP"){
        $("#testInTaskForm #testInfo").val(JSON.stringify($("#"+$("#type").val()+"Form").serializeObject()));
    }
    var flag1 =$("#testInTaskForm").validationAjax();
    var flag2 =$("#"+$("#type").val()+"Form").validationAjax();
    if(flag1 && flag2){
        $.ajax({
            url:appCtx + "secure/res/task/saveTestInTask.html",
            type:"post",
            data:$("#testInTaskForm").serialize(),
            success:function (data) {
                if(data.result =="OK"){
                    $("#testInTaskModal").modal("hide");
                    typeChange();
                    doSuccess();
                }else{
                    doFail();
                }
            },
            error:function () {
                doFail();
            }
        });
    }
    return flag1;
})


 类似资料: