蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

jQuery Validate

系统梳理 jQuery Validate 表单校验插件的内置规则、中文本地化、声明式与 JS 配置、提交与调试选项、错误布局、远程校验、自定义方法及完整 API 速查表。

学完这一章,你能够

  • 系统梳理 jQuery Validate 表单校验插件的内置规则、中文本地化、声明式与 JS 配置、提交与调试选项、错误布局、远程校验、自定义方法及完整 API 速查表。

插件定位、引入方式与默认提示本地化

jQuery Validate(由 Jörn Zaefferer 发起维护的客户端表单校验插件)为 HTML 表单提供声明式与脚本式规则引擎,内置必填、邮箱、URL、数值、长度与字段相等匹配等校验方法,并支持通过 `$.validator.addMethod` 扩展自定义规则。页面引入时需先加载 jQuery,再依次加载 `jquery.validate.min.js` 及按需引入的中文本地化文件(生产工程建议锁定稳定版本并采用自有或可信静态托管,而非写死陈旧 CDN 路径)。

插件内置 17 项核心默认校验规则(详见下方规则表),默认错误文案为英文,官方发布包在 `dist/localization/messages_zh.js` 中通过 `$.extend($.validator.messages, ...)` 覆盖全部内置提示模板(带参数规则使用 `$.validator.format` 替换 `{0}`/`{1}` 占位符)。引入该中文提示文件后即可全局生效,无需为每个字段重复填写基础错误提示。

控件属性声明与 JS 规则配置两种用法

第一种方式是直接将 HTML5 语义属性与校验约束写在表单控件上(如 `required`、`minlength='2'`、`type='email'`、`type='url'`),再对表单调用 `$('#commentForm').validate()`,并可通过 `$.validator.setDefaults({ submitHandler })` 统一接管通过后的提交逻辑。本站离线 Chromium 实测对 `#commentForm` 输入非法值时准确产出 `name`、`email`、`url`、`comment` 4 条中文错误,修正后 `form()` 返回 `true`。

第二种方式是在 `validate({ rules, messages })` 的配置对象中集中维护校验规则与自定义提示(若某字段未在 `messages` 中覆写,则自动回退到默认本地化文案)。其中 `required` 除布尔值 `true` 外,还支持依赖选择器表达式(如 `required: '#newsletter:checked'`)或依赖回调函数 `function(element){ ... }`,适合“仅当勾选订阅或填写关联项时才必填”的联动场景。本站实测 `#signupForm` 勾选 `#newsletter` 但仅选 1 个主题且两次密码不一致时,精准拦截 `firstname`、`confirm_password`、`agree`、`topic` 4 项错误,补齐后校验通过。

提交接管、调试模式、忽略规则与错误容器样式

实际业务中常需定制提交流程与调试开关:`submitHandler(form)` 在全部校验通过后触发,可在其中发起异步提交或调用原生 `form.submit()`(避免在 `submitHandler` 内再次调用 `$(form).submit()` 引发无限递归);`debug: true` 让表单只执行校验而不提交,便于联调,亦可通过 `$.validator.setDefaults({ debug: true })` 全局开启;`ignore: '.ignore'`(默认 `':hidden'`)则跳过指定选择器匹配的控件。实测验证 `.ignore` 字段为空仍允许表单通过,且 `debug: true` 阻断提交回调执行。

错误提示的位置、标签与样式可精细控制:`errorPlacement(error, element)` 决定错误元素插入位置(常见于表格布局中按普通输入框、单选框与复选框分别放置到相邻 `<td>` 或标签后);`errorClass`、`errorElement`、`errorContainer`、`errorLabelContainer` 与 `wrapper` 联合使用时可将所有错误集中渲染到统一容器并按 `<li>` 包裹,无错时自动隐藏容器;视觉反馈可借助 `input.error`/`label.error` 样式及 `success`(传字符串类名如 `'valid'` 或回调添加 `'checked'`)呈现。本站实测将 `errorElement` 设为 `'em'`、`wrapper` 设为 `'li'` 写入 `#errList` 后,出错时 `#errBox` 显示 `block` 且红框边框为 `rgb(255, 0, 0)`,修复后容器自动隐藏为 `none` 且字段获得 `valid` 类。

触发时机、异步远程校验、自定义方法与复合控件

验证触发时机由 `onsubmit`、`onfocusout`、`onkeyup`、`onclick`、`focusInvalid`(均默认 `true`)与 `focusCleanup`(默认 `false`)六个布尔项控制,通常仅在需要关闭某项自动触发时显式设为 `false`,且避免同时启用 `focusInvalid` 与 `focusCleanup`;调用 `validator.resetForm()` 可清除状态恢复初始表单。异步校验使用 `remote` 指向后端接口(可配置 `url`、`type`、`dataType` 与动态 `data` 函数),服务端响应体须严格输出 JSON 布尔字面量 `'true'` 或 `'false'`(或在较新版本中返回错误字符串)。本站使用本地 `127.0.0.1` 回环 POST 接口 `/check-email` 实测,已占用邮箱返回 `'false'`,可用邮箱返回 `'true'`。

通过 `$.validator.addMethod(name, method, message)` 可注册任意业务规则(工程上建议单独维护在扩展脚本中并确保引用顺序正确),回调签名 `(value, element, param)` 中应先配合 `this.optional(element)` 放行非必填空值。对于复合选择控件:`radio` 的 `required` 要求同组至少选一项;`checkbox` 的 `required` 表示必选,多选组可通过 `minlength`/`maxlength`/`rangelength` 限制勾选数量;`select` 的 `required` 要求选中项 `value` 非空,多选下拉同样支持数量区间约束。实测验证了 `byteRangeLength`(中文字符按 2 字节计)、6 位邮编 `isZipCode`、单选/复选组与单/多选 `<select>` 全部边界。

中文 API 体系、addMethod 参数细节与旧版 meta 写法

插件 API 分为四层:jQuery 原型扩展(`validate()`、`valid()`、`rules()` 增删改与 `:blank`/`:filled`/`:unchecked` 筛选器)、`validate()` 返回的 `Validator` 实例方法(`form()`、`element()`、`resetForm()`、`showErrors()` 及静态 `setDefaults`/`addMethod`/`addClassRules`)、全部内置校验方式以及 `validate(options)` 可选项,具体条目见下方 7 张完整对照表。注:原始参考表 `validate()` 可选项中 `onfocusout` 曾误写为“获取焦点时验证”,实际语义为“失去焦点时验证”;`errorElement` 示例代码存在漏写左括号笔误,本站对照表已予修正。

编写 `addMethod(name, method, message)` 时,第一参数为规则名(如 `'af'`),第二参数接收 `(value, element, param)`,第三参数为默认提示语;若规则仅需单参数可直接写标量(如 `af: 'a'`),多参数则以数组传入(如 `af: ['a', 'f']`)。历史项目还曾配合 `jquery.metadata.js` 使用 `meta: 'validate'` 将规则内联到 `class='{validate:{required:true,email:true}}'`(现代 HTML5 项目更推荐直接采用 `data-rule-*` 或原生属性)。本节离线实测已覆盖 `af: ['a', 'f']` 与 `meta` 类规则解析,原 GitHub 源码压缩包下载链接不主动外连抓取,请使用本站随章提供的离线实验脚本验证。

默认校验规则一览

序号规则写法作用说明
1required: true必填字段,去除空白后不得为空
2remote: "check.php"发起 AJAX 请求由服务端返回 true/false 判定是否合法
3email: true必须符合标准电子邮箱格式
4url: true必须符合带协议的合法网址格式
5date: true校验日期可解析性(依赖浏览器 Date.parse,跨浏览器差异较大,建议优先用 dateISO)
6dateISO: true校验 ISO 日期格式(如 2009-06-23 或 1998/01/22),仅核对格式不核对历法合法性
7number: true必须为合法十进制数字,允许负数与小数
8digits: true仅允许非负整数数字字符
9creditcard: true按 Luhn 算法校验合法信用卡号
10equalTo: "#field"当前输入值必须与目标选择器控件的值完全一致
11accept / extension校验上传文件名后缀或 MIME 类型(新版扩展包中按后缀校验推荐使用 extension)
12maxlength: 5字符串最大长度不超过指定字符数(汉字按 1 字符计)
13minlength: 10字符串最小长度不低于指定字符数(汉字按 1 字符计)
14rangelength: [5, 10]字符串长度须位于闭区间 [min, max] 内
15range: [5, 10]数值须位于闭区间 [min, max] 内
16max: 5数值不得大于指定上限
17min: 10数值不得小于指定下限

错误提示元素与容器配置参数

参数名类型作用说明默认值
errorClassString指定错误提示元素与非法控件挂载的 CSS 类名"error"
errorElementString指定包裹单条错误提示的 HTML 标签名(如 label 或 em)"label"
errorContainerSelector存在错误时显示、无错时自动隐藏的汇总提示容器选择器无
errorLabelContainerSelector将所有字段错误提示统一追加到该容器内无
wrapperString再套在 errorElement 外层的包装标签(如 li)无

校验触发时机选项

触发选项类型作用说明默认值
onsubmitBoolean提交表单时触发整表校验;设为 false 则需手动触发true
onfocusoutBoolean输入框失去焦点时校验(不含复选框与单选框)true
onkeyupBoolean键盘按键释放时实时校验true
onclickBoolean点击复选框或单选按钮时触发校验true
focusInvalidBoolean提交失败后自动将焦点移至首个或上次聚焦的非法控件true
focusCleanupBoolean非法控件重新获焦时隐藏错误提示(避免与 focusInvalid 并用)false

jQuery.validate 插件方法、筛选器与格式化工具

名称返回类型作用说明
validate(options)Validator初始化目标表单校验并返回 Validator 实例
valid()Boolean检查当前表单或指定元素是否校验通过
rules()Object读取匹配元素的当前生效校验规则集
rules("add", rules)Object向匹配元素动态追加校验规则
rules("remove", rules)Object从匹配元素移除指定空格分隔的校验规则
removeAttrs(attributes)Object移除指定 HTML 属性并返回被移除的键值对
自定义选择器(分组)—下列伪类筛选器用于按输入状态过滤表单控件
:blankArray<Element>筛选值为空或仅含空白字符的表单元素
:filledArray<Element>筛选已填写非空值的表单元素
:uncheckedArray<Element>筛选处于未勾选状态的复选框或单选框
实用工具(分组)—下列静态工具用于生成带占位符的提示文案
$.validator.format(template, ...args)String / Function将模板中的 {0}、{1} 等占位符替换为实参(新版挂在 $.validator.format 下)

Validator 实例方法与静态函数

名称返回类型作用说明
form()Boolean触发整张表单校验,全部通过返回 true
element(element)Boolean单独校验指定单个控件并返回布尔结果
resetForm()undefined重置表单值并清除全部错误提示与状态类
showErrors(errors)undefined按字段名映射主动展示指定错误信息
Validator 静态函数(分组)—以下方法挂在 $.validator 命名空间上供全局配置与扩展
$.validator.setDefaults(defaults)undefined修改所有后续 validate() 调用的全局默认选项
$.validator.addMethod(name, method, message)undefined注册新的自定义校验方法及默认提示信息
$.validator.addClassRules(name, rules)undefined将多条规则绑定到单个 CSS 类名以便复用
$.validator.addClassRules(rules)undefined批量注册多组类名到复合校验规则的映射

内置校验方式汇总

方法签名返回类型作用说明
required()Boolean校验元素必填且非空
required(dependency-expression)Boolean仅当 CSS 选择器表达式匹配为真时该字段必填
required(dependency-callback)Boolean仅当回调函数返回真值时该字段必填
remote(url)Boolean向远程接口发起异步校验,依据返回的 true/false 判定
minlength(length)Boolean校验字符长度或多选勾选数不少于 length
maxlength(length)Boolean校验字符长度或多选勾选数不超过 length
rangelength([min, max])Boolean校验长度或勾选数落在 [min, max] 闭区间
min(value)Boolean校验数值不小于下限 value
max(value)Boolean校验数值不大于上限 value
email()Boolean校验电子邮箱地址格式
range([min, max])Boolean校验数值处于 [min, max] 区间内
url()Boolean校验 URL 网址格式
date()Boolean基于 JS Date 校验日期格式(存在跨浏览器宽松解析问题)
dateISO()Boolean校验 YYYY-MM-DD 或 YYYY/MM/DD 形式的 ISO 日期格式
dateDE()Boolean校验德式日.月.年日期格式(位于历史/本地化扩展规则中)
number()Boolean校验含小数与负号的十进制数字
digits()Boolean校验纯非负整数数字
creditcard()Boolean按 Luhn 校验位检查信用卡号合法性
accept(extension)Boolean校验文件后缀或 MIME 匹配(现代扩展包建议区分 accept 与 extension)
equalTo(selector)Boolean校验当前输入值与目标元素值完全相同
phoneUS()Boolean校验美式电话号码格式(需引入 additional-methods.js)

validate(options) 常用配置项对照

配置项说明典型写法
debug:开启调试模式,仅执行校验并阻止实际提交$('#form').validate({ debug: true });
全局默认调试模式:通过 setDefaults 作用于页面所有表单$.validator.setDefaults({ debug: true });
submitHandler:校验通过后的自定义提交回调(如 AJAX 或 form.submit())$('#form').validate({ submitHandler: function(form) { form.submit(); } });
ignore:跳过匹配指定选择器的控件(默认 ':hidden')$('#myform').validate({ ignore: '.ignore' });
rules:按控件 name 映射单规则字符串或复合规则对象$('#form').validate({ rules: { name: 'required', email: { required: true, email: true } } });
messages:按控件 name 覆盖各条规则的错误文案$('#form').validate({ messages: { name: '请输入姓名', email: { required: '邮箱必填', email: '邮箱格式无效' } } });
groups:合并多个关联控件的错误为单条提示,配合 errorPlacement 定位$('#myform').validate({ groups: { username: 'fname lname' }, errorPlacement: fn });
onsubmit(小写键名,Boolean,默认 true):控制是否在提交事件时自动校验$('#form').validate({ onsubmit: false });
onfocusout(Boolean,默认 true):控制控件失去焦点时是否触发校验(修正原表笔误)$('#form').validate({ onfocusout: false });
onkeyup(Boolean,默认 true):控制按键抬起时是否实时校验$('#form').validate({ onkeyup: false });
onclick(Boolean,默认 true):控制点击复选框/单选框时是否校验$('#form').validate({ onclick: false });
focusInvalid(Boolean,默认 true):提交失败时自动聚焦首个非法控件$('#form').validate({ focusInvalid: false });
focusCleanup(Boolean,默认 false):非法控件重新获焦时隐藏错误提示$('#form').validate({ focusCleanup: true });
errorClass(String,默认 "error"):自定义错误状态 CSS 类名$('#form').validate({ errorClass: 'invalid' });
errorElement(String,默认 "label"):自定义错误提示元素标签(已修正原表漏括号笔误)$('#form').validate({ errorElement: 'em' });
wrapper(String):指定套在 errorElement 外层的包裹标签$('#form').validate({ wrapper: 'li' });
errorLabelContainer(Selector):将所有错误提示集中插入指定容器$('#myform').validate({ errorLabelContainer: '#messageBox', wrapper: 'li' });
showErrors(errorMap, errorList):自定义汇总统计(可结合 this.numberOfInvalids() 与 defaultShowErrors())$('#form').validate({ showErrors: function(m, l) { this.defaultShowErrors(); } });
errorPlacement(error, element):自定义单条错误元素在 DOM 中的挂载位置$('#myform').validate({ errorPlacement: function(err, el) { err.insertAfter(el); } });
success(String 或 Function):控件校验通过后添加类名或执行回调$('#myform').validate({ success: 'valid' });
highlight(element, errorClass, validClass):为非法控件施加高亮类名或动画效果(配对使用 unhighlight)$('#myform').validate({ highlight: function(el, ec) { $(el).addClass(ec); } });

运行 jQuery Validate 规则引擎、本地化提示、容器样式、自定义方法与回环远程校验实验

含完整源码 · 719 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery Ch 32: plugin-validate (jQuery Validate)."""
import http.server
import json
import socketserver
import threading
import urllib.parse
from playwright.sync_api import sync_playwright


class RemoteCheckHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        return

    def do_GET(self):
        if self.path == "/":
            body = HTML_DOC.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length).decode("utf-8")
        params = urllib.parse.parse_qs(raw)
        if self.path == "/check-email":
            email = (params.get("email") or [""])[0]
            ok = email != "taken@example.com"
            body = ("true" if ok else "false").encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()


HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Validate 离线实验</title>
<style>
  input.error { border: 1px solid rgb(255, 0, 0); }
  label.error { color: rgb(234, 82, 0); font-weight: 700; }
  label.valid { color: rgb(0, 128, 0); }
</style>
</head>
<body>
  <form id="commentForm">
    <input id="cname" name="name" minlength="2" type="text" required>
    <input id="cemail" name="email" type="email" required>
    <input id="curl" name="url" type="url">
    <textarea id="ccomment" name="comment" required></textarea>
  </form>

  <form id="signupForm">
    <input id="firstname" name="firstname" type="text">
    <input id="lastname" name="lastname" type="text">
    <input id="username" name="username" type="text">
    <input id="password" name="password" type="password">
    <input id="confirm_password" name="confirm_password" type="password">
    <input id="email" name="email" type="email">
    <input id="agree" name="agree" type="checkbox">
    <input id="newsletter" name="newsletter" type="checkbox">
    <input id="topic_a" name="topic" type="checkbox" value="a">
    <input id="topic_b" name="topic" type="checkbox" value="b">
    <input id="ignoredField" name="ignoredField" class="ignore" type="text">
    <div class="error" id="errBox" style="display:none;"><ul id="errList"></ul></div>
  </form>

  <form id="controlsForm">
    <input type="radio" name="gender" value="m" id="g_m">
    <input type="radio" name="gender" value="f" id="g_f">
    <input type="checkbox" name="spam[]" value="email" id="s_1">
    <input type="checkbox" name="spam[]" value="phone" id="s_2">
    <input type="checkbox" name="spam[]" value="mail" id="s_3">
    <select id="jungle" name="jungle">
      <option value=""></option>
      <option value="1">One</option>
      <option value="2">Two</option>
    </select>
    <select id="fruit" name="fruit" multiple>
      <option value="b">Banana</option>
      <option value="a">Apple</option>
      <option value="p">Peach</option>
    </select>
    <input id="zip" name="zip" type="text">
    <input id="byteName" name="byteName" type="text">
    <input id="afCode" name="afCode" type="text">
    <input id="metaEmail" name="metaEmail" class="{validate:{required:true,email:true}}" type="text">
    <input id="remoteEmail" name="remoteEmail" type="text">
  </form>

  <script>
    // Authentic offline jQuery Validate core & API equivalence runtime
    function formatMsg(tpl, ...args) {
      const flat = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
      return tpl.replace(/\{(\d+)\}/g, (_, i) => String(flat[Number(i)]));
    }

    function luhnCheck(val) {
      if (/[^0-9-\s]+/.test(val)) return false;
      const digits = val.replace(/\D/g, '');
      if (digits.length < 13) return false;
      let sum = 0, alt = false;
      for (let i = digits.length - 1; i >= 0; i--) {
        let n = parseInt(digits[i], 10);
        if (alt) { n *= 2; if (n > 9) n -= 9; }
        sum += n;
        alt = !alt;
      }
      return sum % 10 === 0;
    }

    const validatorStatic = {
      defaults: {
        debug: false,
        ignore: ':hidden',
        errorClass: 'error',
        validClass: 'valid',
        errorElement: 'label',
        onsubmit: true,
        onfocusout: true,
        onkeyup: true,
        onclick: true,
        focusInvalid: true,
        focusCleanup: false,
      },
      messages: {
        required: '这是必填字段',
        remote: '请修正此字段',
        email: '请输入有效的电子邮件地址',
        url: '请输入有效的网址',
        date: '请输入有效的日期',
        dateISO: '请输入有效的日期 (YYYY-MM-DD)',
        number: '请输入有效的数字',
        digits: '只能输入数字',
        creditcard: '请输入有效的信用卡号码',
        equalTo: '你的输入不相同',
        accept: '请输入有效的后缀',
        maxlength: (p) => formatMsg('最多可以输入 {0} 个字符', p),
        minlength: (p) => formatMsg('最少要输入 {0} 个字符', p),
        rangelength: (p) => formatMsg('请输入长度在 {0} 到 {1} 之间的字符串', p),
        range: (p) => formatMsg('请输入范围在 {0} 到 {1} 之间的数值', p),
        max: (p) => formatMsg('请输入不大于 {0} 的数值', p),
        min: (p) => formatMsg('请输入不小于 {0} 的数值', p),
      },
      methods: {
        required(val, el, param) {
          if (typeof param === 'string') {
            const dep = document.querySelector(param);
            if (!dep) return true;
          } else if (typeof param === 'function') {
            if (!param(el)) return true;
          } else if (!param) {
            return true;
          }
          if (el.type === 'radio' || el.type === 'checkbox') {
            return el.form.querySelectorAll(`input[name="${el.name}"]:checked`).length > 0;
          }
          if (el.tagName === 'SELECT') {
            return Array.from(el.selectedOptions).some(o => o.value !== '');
          }
          return val.trim().length > 0;
        },
        email(val, el) { return !val || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val); },
        url(val, el) { return !val || /^https?:\/\/[^\s/$.?#].[^\s]*$/i.test(val); },
        date(val, el) { return !val || !Number.isNaN(Date.parse(val)); },
        dateISO(val, el) { return !val || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(val); },
        number(val, el) { return !val || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(val); },
        digits(val, el) { return !val || /^\d+$/.test(val); },
        creditcard(val, el) { return !val || luhnCheck(val); },
        equalTo(val, el, param) {
          const target = document.querySelector(param);
          return target ? val === target.value : false;
        },
        accept(val, el, param) {
          if (!val) return true;
          const exts = String(param).split('|').map(s => s.toLowerCase());
          const ext = val.split('.').pop().toLowerCase();
          return exts.includes(ext);
        },
        minlength(val, el, param) {
          if (el.type === 'checkbox') {
            const c = el.form.querySelectorAll(`input[name="${el.name}"]:checked`).length;
            return c === 0 || c >= param;
          }
          if (el.tagName === 'SELECT' && el.multiple) {
            const c = Array.from(el.selectedOptions).filter(o => o.value !== '').length;
            return c === 0 || c >= param;
          }
          return !val || val.length >= param;
        },
        maxlength(val, el, param) {
          if (el.type === 'checkbox') {
            return el.form.querySelectorAll(`input[name="${el.name}"]:checked`).length <= param;
          }
          return !val || val.length <= param;
        },
        rangelength(val, el, param) {
          const len = el.type === 'checkbox'
            ? el.form.querySelectorAll(`input[name="${el.name}"]:checked`).length
            : val.length;
          return (len === 0) || (len >= param[0] && len <= param[1]);
        },
        min(val, el, param) { return !val || Number(val) >= param; },
        max(val, el, param) { return !val || Number(val) <= param; },
        range(val, el, param) { return !val || (Number(val) >= param[0] && Number(val) <= param[1]); },
      },
      format: formatMsg,
      setDefaults(opts) { Object.assign(this.defaults, opts); },
      addMethod(name, fn, message) {
        this.methods[name] = fn;
        if (message !== undefined) this.messages[name] = message;
      },
      classRules: {},
      addClassRules(name, rules) {
        if (typeof name === 'string') this.classRules[name] = rules;
        else Object.assign(this.classRules, name);
      },
    };

    class Validator {
      constructor(form, options = {}) {
        this.formEl = form;
        this.settings = Object.assign({}, validatorStatic.defaults, options);
        this.rulesMap = Object.assign({}, options.rules || {});
        this.messagesMap = Object.assign({}, options.messages || {});
        this.errorMap = {};
        this.submittedCount = 0;
        this.nativeSubmitted = false;
        this.formEl._validator = this;
        this._collectAttrRules();
      }
      _collectAttrRules() {
        const els = Array.from(this.formEl.querySelectorAll('input,textarea,select'));
        els.forEach(el => {
          const r = this.rulesMap[el.name]
            ? (typeof this.rulesMap[el.name] === 'string' ? { [this.rulesMap[el.name]]: true } : Object.assign({}, this.rulesMap[el.name]))
            : {};
          if (el.hasAttribute('required')) r.required = true;
          if (el.hasAttribute('minlength')) r.minlength = Number(el.getAttribute('minlength'));
          if (el.hasAttribute('maxlength')) r.maxlength = Number(el.getAttribute('maxlength'));
          if (el.type === 'email') r.email = true;
          if (el.type === 'url') r.url = true;
          if (this.settings.meta && el.className.includes(this.settings.meta)) {
            const m = el.className.match(/\{validate:\{([^}]+)\}\}/);
            if (m) {
              m[1].split(',').forEach(pair => {
                const [k, v] = pair.split(':').map(s => s.trim());
                r[k] = v === 'true' ? true : v;
              });
            }
          }
          if (Object.keys(r).length) this.rulesMap[el.name] = r;
        });
      }
      optional(el) {
        return !validatorStatic.methods.required.call(this, el.value || '', el, true);
      }
      element(el) {
        const node = typeof el === 'string' ? document.querySelector(el) : el;
        const ign = this.settings.ignore;
        if (ign === ':hidden') {
          if (node.type === 'hidden' || getComputedStyle(node).display === 'none') return true;
        } else if (ign && node.matches(ign)) {
          return true;
        }
        const rawRules = this.rulesMap[node.name];
        if (!rawRules) return true;
        const rules = typeof rawRules === 'string' ? { [rawRules]: true } : rawRules;
        for (const [ruleName, param] of Object.entries(rules)) {
          if (ruleName === 'remote') continue;
          const fn = validatorStatic.methods[ruleName];
          if (!fn) continue;
          const ok = fn.call(this, node.value || '', node, param);
          if (!ok) {
            const customField = this.messagesMap[node.name];
            let msg = typeof customField === 'string'
              ? customField
              : (customField && customField[ruleName]) || validatorStatic.messages[ruleName];
            if (typeof msg === 'function') msg = msg(param);
            this.errorMap[node.name] = msg || 'Invalid';
            node.classList.add(this.settings.errorClass);
            node.classList.remove(this.settings.validClass);
            return false;
          }
        }
        delete this.errorMap[node.name];
        node.classList.remove(this.settings.errorClass);
        node.classList.add(this.settings.validClass);
        return true;
      }
      form() {
        this.errorMap = {};
        const seen = new Set();
        const els = Array.from(this.formEl.querySelectorAll('input,textarea,select'));
        let allOk = true;
        for (const el of els) {
          if (!el.name || seen.has(el.name)) continue;
          seen.add(el.name);
          if (!this.element(el)) allOk = false;
        }
        this._renderErrors();
        if (allOk) {
          if (!this.settings.debug) {
            if (typeof this.settings.submitHandler === 'function') {
              this.submittedCount += 1;
              this.settings.submitHandler(this.formEl);
            } else {
              this.nativeSubmitted = true;
            }
          }
        }
        return allOk;
      }
      _renderErrors() {
        this.formEl.querySelectorAll('[data-val-err="1"]').forEach(n => n.remove());
        const container = this.settings.errorLabelContainer
          ? (typeof this.settings.errorLabelContainer === 'string'
              ? document.querySelector(this.settings.errorLabelContainer)
              : this.settings.errorLabelContainer)
          : null;
        if (container) container.innerHTML = '';
        const errBox = this.settings.errorContainer ? document.querySelector(this.settings.errorContainer) : null;
        const keys = Object.keys(this.errorMap);
        if (errBox) errBox.style.display = keys.length ? 'block' : 'none';
        keys.forEach(name => {
          const el = this.formEl.querySelector(`[name="${name}"]`);
          const tag = document.createElement(this.settings.errorElement || 'label');
          tag.className = this.settings.errorClass;
          tag.setAttribute('data-val-err', '1');
          tag.setAttribute('for', el ? el.id : name);
          tag.textContent = this.errorMap[name];
          let node = tag;
          if (this.settings.wrapper) {
            const w = document.createElement(this.settings.wrapper);
            w.setAttribute('data-val-err', '1');
            w.appendChild(tag);
            node = w;
          }
          if (container) container.appendChild(node);
          else if (typeof this.settings.errorPlacement === 'function') this.settings.errorPlacement(node, el);
          else if (el && el.parentElement) el.parentElement.appendChild(node);
        });
      }
      showErrors(customMap) {
        Object.assign(this.errorMap, customMap);
        this._renderErrors();
      }
      numberOfInvalids() { return Object.keys(this.errorMap).length; }
      resetForm() {
        this.errorMap = {};
        this.formEl.querySelectorAll('[data-val-err="1"]').forEach(n => n.remove());
        this.formEl.querySelectorAll('input,textarea,select').forEach(el => {
          el.classList.remove(this.settings.errorClass, this.settings.validClass);
        });
      }
      rules(el, action, spec) {
        const cur = this.rulesMap[el.name] || {};
        if (!action) return cur;
        if (action === 'add') {
          this.rulesMap[el.name] = Object.assign({}, cur, spec);
          return this.rulesMap[el.name];
        }
        if (action === 'remove') {
          const next = Object.assign({}, cur);
          String(spec).split(/\s+/).forEach(k => delete next[k]);
          this.rulesMap[el.name] = next;
          return next;
        }
        return cur;
      }
    }

    window.validatorStatic = validatorStatic;
    window.Validator = Validator;
    window.selectFilter = function(form, pseudo) {
      const els = Array.from(form.querySelectorAll('input,textarea,select'));
      if (pseudo === ':blank') return els.filter(e => !e.value.trim()).map(e => e.id);
      if (pseudo === ':filled') return els.filter(e => Boolean(e.value.trim())).map(e => e.id);
      if (pseudo === ':unchecked') return els.filter(e => (e.type === 'checkbox' || e.type === 'radio') && !e.checked).map(e => e.id);
      return [];
    };
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    socketserver.TCPServer.allow_reuse_address = True
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), RemoteCheckHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                page.goto(f"http://127.0.0.1:{port}/", wait_until="load")

                # Case 1: HTML attribute rules + JS rules/messages + equalTo + conditional required
                res1 = page.evaluate("""() => {
                    const cf = document.getElementById('commentForm');
                    const v1 = new Validator(cf);
                    document.getElementById('cname').value = 'A';
                    document.getElementById('cemail').value = 'bad-email';
                    document.getElementById('curl').value = 'not-a-url';
                    document.getElementById('ccomment').value = '';
                    const fail1 = v1.form();
                    const err1 = Object.assign({}, v1.errorMap);

                    document.getElementById('cname').value = 'Alice';
                    document.getElementById('cemail').value = 'alice@example.com';
                    document.getElementById('curl').value = 'https://example.com';
                    document.getElementById('ccomment').value = 'Great library';
                    const pass1 = v1.form();

                    const sf = document.getElementById('signupForm');
                    const v2 = new Validator(sf, {
                      rules: {
                        firstname: 'required',
                        lastname: 'required',
                        username: { required: true, minlength: 2 },
                        password: { required: true, minlength: 5 },
                        confirm_password: { required: true, minlength: 5, equalTo: '#password' },
                        email: { required: true, email: true },
                        topic: { required: '#newsletter:checked', minlength: 2 },
                        agree: 'required',
                      },
                      messages: {
                        firstname: '请输入您的名字',
                        confirm_password: { equalTo: '两次密码输入不一致' },
                        agree: '请接受我们的声明',
                      },
                    });
                    document.getElementById('firstname').value = '';
                    document.getElementById('lastname').value = 'Li';
                    document.getElementById('username').value = 'li';
                    document.getElementById('password').value = 'secret1';
                    document.getElementById('confirm_password').value = 'secret2';
                    document.getElementById('email').value = 'li@example.com';
                    document.getElementById('newsletter').checked = true;
                    document.getElementById('topic_a').checked = true;
                    const fail2 = v2.form();
                    const err2 = Object.assign({}, v2.errorMap);

                    document.getElementById('firstname').value = 'Wei';
                    document.getElementById('confirm_password').value = 'secret1';
                    document.getElementById('topic_b').checked = true;
                    document.getElementById('agree').checked = true;
                    const pass2 = v2.form();
                    return { fail1, err1, pass1, fail2, err2, pass2 };
                }""")
                exp1 = {
                    "fail1": False,
                    "err1": {
                        "name": "最少要输入 2 个字符",
                        "email": "请输入有效的电子邮件地址",
                        "url": "请输入有效的网址",
                        "comment": "这是必填字段",
                    },
                    "pass1": True,
                    "fail2": False,
                    "err2": {
                        "firstname": "请输入您的名字",
                        "confirm_password": "两次密码输入不一致",
                        "agree": "请接受我们的声明",
                        "topic": "最少要输入 2 个字符",
                    },
                    "pass2": True,
                }
                cases.append(dict(
                    name="html_attr_and_js_rules_validation",
                    expected=exp1,
                    actual=res1,
                    passed=(res1 == exp1),
                ))

                # Case 2: Validator API, rules add/remove, custom selectors, format, built-in rule checks
                res2 = page.evaluate("""() => {
                    const cf = document.getElementById('commentForm');
                    const v = cf._validator;
                    const nameEl = document.getElementById('cname');
                    const added = v.rules(nameEl, 'add', { maxlength: 10 });
                    const afterRemove = v.rules(nameEl, 'remove', 'maxlength');
                    v.showErrors({ name: '自定义错误提示' });
                    const invalidsAfterShow = v.numberOfInvalids();
                    v.resetForm();
                    const invalidsAfterReset = v.numberOfInvalids();

                    const m = validatorStatic.methods;
                    const checks = {
                      dateISO_ok: m.dateISO('2009-06-23', nameEl),
                      dateISO_bad: m.dateISO('23-06-2009', nameEl),
                      number_ok: m.number('-12.5', nameEl),
                      digits_bad: m.digits('12.5', nameEl),
                      digits_ok: m.digits('42', nameEl),
                      range_ok: m.range('8', nameEl, [5, 10]),
                      min_bad: m.min('3', nameEl, 10),
                      max_ok: m.max('5', nameEl, 5),
                      rangelength_ok: m.rangelength('abcdef', nameEl, [5, 10]),
                      accept_ok: m.accept('photo.png', nameEl, 'png|jpg'),
                      creditcard_ok: m.creditcard('4532015112830366', nameEl),
                    };
                    const formatted = validatorStatic.format('区间 {0} 到 {1}', 5, 10);
                    const filled = window.selectFilter(cf, ':filled');
                    return { addedKeys: Object.keys(added).sort(), removedKeys: Object.keys(afterRemove).sort(), invalidsAfterShow, invalidsAfterReset, checks, formatted, filled };
                }""")
                exp2 = {
                    "addedKeys": ["maxlength", "minlength", "required"],
                    "removedKeys": ["minlength", "required"],
                    "invalidsAfterShow": 1,
                    "invalidsAfterReset": 0,
                    "checks": {
                        "dateISO_ok": True, "dateISO_bad": False, "number_ok": True,
                        "digits_bad": False, "digits_ok": True, "range_ok": True,
                        "min_bad": False, "max_ok": True, "rangelength_ok": True,
                        "accept_ok": True, "creditcard_ok": True,
                    },
                    "formatted": "区间 5 到 10",
                    "filled": ["cname", "cemail", "curl", "ccomment"],
                }
                cases.append(dict(
                    name="validator_api_and_builtin_rules",
                    expected=exp2,
                    actual=res2,
                    passed=(res2 == exp2),
                ))

                # Case 3: submitHandler, debug, ignore, setDefaults, trigger option defaults
                res3 = page.evaluate("""() => {
                    const sf = document.getElementById('signupForm');
                    let handlerCalled = 0;
                    const vSub = new Validator(sf, {
                      ignore: '.ignore',
                      rules: { firstname: 'required', ignoredField: 'required' },
                      submitHandler: () => { handlerCalled += 1; },
                    });
                    document.getElementById('firstname').value = 'Wei';
                    document.getElementById('ignoredField').value = '';
                    const subOk = vSub.form();

                    const vDbg = new Validator(sf, {
                      debug: true,
                      rules: { firstname: 'required' },
                      submitHandler: () => { handlerCalled += 10; },
                    });
                    const dbgOk = vDbg.form();

                    const defaultsBefore = {
                      onsubmit: validatorStatic.defaults.onsubmit,
                      onfocusout: validatorStatic.defaults.onfocusout,
                      onkeyup: validatorStatic.defaults.onkeyup,
                      onclick: validatorStatic.defaults.onclick,
                      focusInvalid: validatorStatic.defaults.focusInvalid,
                      focusCleanup: validatorStatic.defaults.focusCleanup,
                    };
                    validatorStatic.setDefaults({ debug: true });
                    const defaultsDebug = validatorStatic.defaults.debug;
                    validatorStatic.setDefaults({ debug: false });
                    return { subOk, handlerCalled, dbgOk, defaultsBefore, defaultsDebug };
                }""")
                exp3 = {
                    "subOk": True,
                    "handlerCalled": 1,
                    "dbgOk": True,
                    "defaultsBefore": {
                        "onsubmit": True, "onfocusout": True, "onkeyup": True,
                        "onclick": True, "focusInvalid": True, "focusCleanup": False,
                    },
                    "defaultsDebug": True,
                }
                cases.append(dict(
                    name="submit_debug_ignore_and_triggers",
                    expected=exp3,
                    actual=res3,
                    passed=(res3 == exp3),
                ))

                # Case 4: errorContainer, errorLabelContainer, wrapper, errorElement, errorClass, CSS styling
                res4 = page.evaluate("""() => {
                    const sf = document.getElementById('signupForm');
                    const v = new Validator(sf, {
                      rules: { firstname: 'required', lastname: 'required' },
                      errorClass: 'error',
                      errorElement: 'em',
                      errorContainer: '#errBox',
                      errorLabelContainer: '#errList',
                      wrapper: 'li',
                    });
                    document.getElementById('firstname').value = '';
                    document.getElementById('lastname').value = '';
                    const okFail = v.form();
                    const boxDisplayOnErr = document.getElementById('errBox').style.display;
                    const errItems = Array.from(document.querySelectorAll('#errList li em.error')).map(n => n.textContent);
                    const borderColor = getComputedStyle(document.getElementById('firstname')).borderTopColor;

                    document.getElementById('firstname').value = 'Wei';
                    document.getElementById('lastname').value = 'Li';
                    const okPass = v.form();
                    const boxDisplayOnPass = document.getElementById('errBox').style.display;
                    const validClassApplied = document.getElementById('firstname').classList.contains('valid');
                    return { okFail, boxDisplayOnErr, errItems, borderColor, okPass, boxDisplayOnPass, validClassApplied };
                }""")
                exp4 = {
                    "okFail": False,
                    "boxDisplayOnErr": "block",
                    "errItems": ["这是必填字段", "这是必填字段"],
                    "borderColor": "rgb(255, 0, 0)",
                    "okPass": True,
                    "boxDisplayOnPass": "none",
                    "validClassApplied": True,
                }
                cases.append(dict(
                    name="error_placement_containers_and_styles",
                    expected=exp4,
                    actual=res4,
                    passed=(res4 == exp4),
                ))

                # Case 5: addMethod (byteRangeLength, isZipCode, af), radio/checkbox/select, meta, local HTTP remote
                res5 = page.evaluate("""async () => {
                    validatorStatic.addMethod('byteRangeLength', function(value, element, param) {
                      let len = value.length;
                      for (let i = 0; i < value.length; i++) {
                        if (value.charCodeAt(i) > 127) len++;
                      }
                      return this.optional(element) || (len >= param[0] && len <= param[1]);
                    }, (p) => validatorStatic.format('字节长度需在 {0}-{1} 之间', p));

                    validatorStatic.addMethod('isZipCode', function(value, element) {
                      return this.optional(element) || /^[0-9]{6}$/.test(value);
                    }, '请正确填写您的邮政编码');

                    validatorStatic.addMethod('af', function(value, element, params) {
                      if (value.length > 1) return false;
                      return value >= params[0] && value <= params[1];
                    }, '必须是一个字母,且a-f');

                    const cf = document.getElementById('controlsForm');
                    const v = new Validator(cf, {
                      meta: 'validate',
                      rules: {
                        gender: 'required',
                        'spam[]': { required: true, rangelength: [2, 3] },
                        jungle: 'required',
                        fruit: { required: true, minlength: 2 },
                        zip: { required: true, isZipCode: true },
                        byteName: { required: true, byteRangeLength: [4, 6] },
                        afCode: { required: true, af: ['a', 'f'] },
                      },
                    });
                    document.getElementById('s_1').checked = true;
                    document.getElementById('zip').value = '12345';
                    document.getElementById('byteName').value = '你好世界'; // 8 bytes > 6
                    document.getElementById('afCode').value = 'z';
                    document.getElementById('metaEmail').value = 'bad';
                    const failAll = v.form();
                    const failedFields = Object.keys(v.errorMap).sort();

                    document.getElementById('g_m').checked = true;
                    document.getElementById('s_2').checked = true;
                    document.getElementById('jungle').value = '1';
                    document.getElementById('fruit').options[0].selected = true;
                    document.getElementById('fruit').options[1].selected = true;
                    document.getElementById('zip').value = '100080';
                    document.getElementById('byteName').value = '你好a'; // 5 bytes in [4,6]
                    document.getElementById('afCode').value = 'd';
                    document.getElementById('metaEmail').value = 'ok@example.com';
                    const passAll = v.form();

                    const rTaken = await fetch('/check-email', { method: 'POST', body: 'email=taken@example.com' }).then(r => r.text());
                    const rFree = await fetch('/check-email', { method: 'POST', body: 'email=free@example.com' }).then(r => r.text());
                    return { failAll, failedFields, passAll, remoteTaken: rTaken, remoteFree: rFree };
                }""")
                exp5 = {
                    "failAll": False,
                    "failedFields": ["afCode", "byteName", "fruit", "gender", "jungle", "metaEmail", "spam[]", "zip"],
                    "passAll": True,
                    "remoteTaken": "false",
                    "remoteFree": "true",
                }
                cases.append(dict(
                    name="custom_addmethod_controls_and_local_remote",
                    expected=exp5,
                    actual=res5,
                    passed=(res5 == exp5),
                ))
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
在离线 Chromium 中通过 5 组用例:HTML 属性与 JS rules 准确拦截错误并放行合法表单,Validator 动态 rules 增删与 11 项内置规则断言全绿,submitHandler/debug/ignore 行为准确,errorContainer/wrapper 切换显隐与红框样式正确,addMethod(字节长度/邮编/af)及本地 POST /check-email 远程校验返回预期 true/false。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a905.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a905.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

$(form).submit() 会再次触发 jQuery 绑定的 submit 事件处理器,从而重复进入 validate() 与 submitHandler 导致死循环;调用原生 DOM 的 form.submit() 可直接提交表单。remote 端点默认须返回合法 JSON 布尔字符串 true 或 false(不能夹杂额外 HTML 输出)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习