蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-plugin-validate.py
explore-plugin-validate.py719 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jquery-plugin-validate-lab/explore-plugin-validate.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-plugin-validate.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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