jQuery Validate是一个jquery的校验工具,这里就不做过多介绍,想详细了解可以前往菜鸟教程查看相关Api,建议先看,再用

这是一个jQuery Validate 的案列!

  1. 导入相关js库,可以前往菜鸟教程。

  2. 编写html

使用前提:

  • formVerify.js这个js是编写相关校验的js。

  • additional-methods.js 这个js是自定义规则的js。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>form_verify</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
    <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
    <script src="js/formVerify.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/additional-methods.js"></script>
    <style>
      label.error {
        color: #EA5200;
      }
    </style>
  </head>
  <body>
    <!-- 基本校验 -->
    <form id="formTest">
      <div class="modal" style="display: inline;">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">表单校验测试01</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">姓名</span>
                </div>
                <input type="text" class="form-control" name="name">
              </div>

              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">数量</span>
                </div>
                <input type="text" class="form-control" name="num">
              </div>

              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">文件</span>
                </div>
                <div class="custom-file">
                  <input type="file" name="img">
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" id="subBtn" class="btn btn-primary">提交</button>
            </div>
          </div>
        </div>
      </div>
    </form>

    <!-- 时间校验 -->
    <form id="form_time">
      <div class="modal" style="display: inline;margin-top: 20%;">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">表单校验测试02</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">开始时间</span>
                </div>
                <input type="text" class="form-control" name="startTime" id="startTime">
              </div>

              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">结束时间</span>
                </div>
                <input type="text" class="form-control" name="endTime">
              </div>

              <div class="input-group mb-3">
                <div class="input-group-prepend">
                  <span class="input-group-text">字母</span>
                </div>
                <div class="custom-file">
                  <input type="text" name="ygroup">
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-primary">提交</button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </body>
</html>


  1. 编写js

//formVerify.js

$(function() {
  
  //这个校验因为是使用的submit提交方式,所以在页面加载的时候就要放出来。
  validform_time("form_time")
  
  $("#subBtn").click(function() {
    //这里是不通过submit提交,一般是结合ajax
    let flg = validform("formTest").form();
    if (flg) {
      //$.ajax()...
      console.log(true)
    } else {
      conso.log(false)
    }
  })
})

//声明一个函数
function validform(fromid) {
  //这里是基本结构介绍,其中有使用到自定义校验
  return $("#" + fromid).validate({
    rules: {
      //名称
      name: {
        required: true,
        minlength: 2
      },
      //积分规则管理 年积分管理(积分增量值)
      num: {
        required: true,
        number: true
      },
      //图片校验
      img: {
        required: true,
        accept: "jpg|png|jpeg"
      },

    },
    messages: {
      name: {
        required: "必填",
        minlength: "必需由两个字符组成"
      },
      num: {
        required: "必填",
        number: "必须输入合法的数字"
      },
      //图片校验
      img: {
        required: "必填",
        accept: "请上传格式为:jpg/png/jpeg/gif 的图片"
      },
    }
  });
}

function validform_upload(fromid) {
  //这里是上传文件后缀校验,使用的是自定义校验
  return $("#" + fromid).validate({
    rules: {
      yearintegral: {
        required: true,
        accept: "xls"
      },
    },
    messages: {
      yearintegral: {
        required: "必填",
        accept: "请上传.xls的文件"
      },

    },
    //更改错误显示的位置,这个案列中效果不明显,可以查看文档详细了解
    errorPlacement: function(error, element) {
      error.insertAfter("#" + fromid + " .modal-body label");
    }
  });
}

function validform_time(fromid) {
  //这里是校验时间,使用的是自定义校验,注意看这里没有返回值,说明直接调用即可使用,
  $("#" + fromid).validate({
    rules: {
      // 开始时间和结束时间都必须填写
      startTime: {
        required: true,
        dateFormat1: true
      },
      // 结束时间必须晚于开始时间
      endTime: {
        required: true,
        //注意这个,必须是id,自定义规则中 通过id获取到了开始时间的值
        greaterThan: "#startTime",
        dateFormat1: true
      },
      ygroup: {
        required: true,
        uppercase: true
      }
    },
    messages: {
      startTime: {
        required: "请输入开始时间",
        dateFormat1:"请按该格式输入:2022/8/20"
      },
      endTime: {
        required: "请输入结束时间",
        dateFormat1:"请按该格式输入:2022/8/20",
        greaterThan: "结束时间必须晚于开始时间",
      },
      ygroup: {
        required: "必填",
        uppercase: "请输入A/B/C....Z"
      }
    },
  });
}
  1. 自定义规则js additional-methods.js

//校验上传格式
$.validator.addMethod("accept", function(value, element, param) {
  param = typeof param === "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
  return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
}, $.validator.format("请选择一个有效的文件格式."));

// 自定义校验方法 greaterThan(结束时间必须晚于开始时间)
$.validator.addMethod("greaterThan", function(value, element, param) {
  var startDate = $(param).val();
  console.log(startDate)
  if (startDate) {
    return new Date(value) > new Date(startDate);
  }
  return true;
}, "结束时间必须晚于开始时间");

//校验时间日期
jQuery.validator.addMethod("dateFormat1", function(value, element) {
  console.log(value)
  return this.optional(element) || /^\d{4}\/(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])$/.test(value);
  //return this.optional(element) || /^\d{4}\/\d{2}\/\d{2}$/.test(value); 2022/08/20
}, "请输入正确的日期格式,例如:2022/8/20");

jQuery.validator.addMethod("dateFormat2", function(value, element) {
  return this.optional(element) || /^(\d{4})-(\d{2})-(\d{2})$/.test(value);
}, "时间格式应为yyyy-mm-dd");

//校验字母
$.validator.addMethod("uppercase", function(value, element) {
  return this.optional(element) || /^[A-Z]{0,24}$/.test(value);
}, "请输入24个大写英文");