You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery实现输入以0x开头且长度为42位的校验

解决方案:满足输入框以0x开头且长度42位的校验要求

要实现输入框内容必须以0x开头且总长度为42位的校验,只需修改输入事件的判断逻辑,同时校验两个核心条件即可,以下是具体修改方案:

修改思路

原代码仅判断了输入长度是否为42位,现在需要新增两个关键校验点:

  • 输入内容必须以0x开头
  • 总长度严格等于42位(0x占2位,剩余40位为用户输入内容)

方式一:字符串方法直接判断

利用JavaScript原生startsWith()方法判断开头,结合长度校验,逻辑简单直观:

$("#check").on("input", function (e) {
  const inputVal = this.value.trim(); // 可选:去除首尾空格,避免无效空格干扰
  // 同时满足长度42、以0x开头两个条件
  if (inputVal.length === 42 && inputVal.startsWith("0x")) {
    $("#kato").prop("disabled", false);
  } else {
    $("#kato").prop("disabled", true);
  }
});

方式二:正则表达式校验(更严谨)

如果需要进一步限制0x之后的字符类型(比如仅允许字母数字),可以用正则表达式/^0x[a-zA-Z0-9]{40}$/,确保0x开头后紧跟40位有效字符,总长度刚好42位:

$("#check").on("input", function (e) {
  const inputVal = this.value.trim();
  const validPattern = /^0x[a-zA-Z0-9]{40}$/;
  if (validPattern.test(inputVal)) {
    $("#kato").prop("disabled", false);
  } else {
    $("#kato").prop("disabled", true);
  }
});

修改后的完整代码

替换原页面中的<script>部分即可,完整代码如下:

<html lang="en-US" class="lang-en" dir="ltr">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <link rel="stylesheet" href="/css/home.css" />
    <script type="text/javascript" src="//code.jquery.com/jquery-compat-git.js"></script>
  </head>

  <body>
    <input type="text" id="check" data-minlength="42" name="address" onKeyDown="javascript: var keycode = keyPressed(event); if(keycode==32){ return false; }" />

    <button class="button button-rounded-rectangle" type="button" id="kato" disabled>Continue</button>

    <script type="text/javascript">
      //<![CDATA[
      $(function () {
        $("#kato").prop("disabled", true);
      
        $("#check").on("input", function (e) {
          const inputVal = this.value.trim();
          const validPattern = /^0x[a-zA-Z0-9]{40}$/;
          if (validPattern.test(inputVal)) {
            $("#kato").prop("disabled", false);
          } else {
            $("#kato").prop("disabled", true);
          }
        });
      });
      //]]>
    </script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者0xWenMoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:27:16