猿问

如何在 Javascript 中的文本 oninput() 上验证 00-00-00-0000 格式

代码在这里正常工作..但根据问题,它实际上无法正常工作我想验证 00-00-00-0000 格式的数字/字母文本..但此代码仅在第一次填充值然后它的工作正确但在明文之后填充值验证工作不正常。


var v = "0";

var v1 = "0";

var v2 = "0";


function myFunction() {

  var x = document.getElementById("vname");

  x.value = x.value.toUpperCase();

  var add = "-";

  var string = x.value;

  var str = "";

  var len = string.length;

  if (len > 13) {

    x.value = string.substring(0, 13);

  }

  if (len > 2 && v == "0") {

    var str = x.value;

    x.value = setCharAt(str, 2, '-');

    v = "1";

  }

  if (len > 5 && v1 == "0") {

    var str = x.value;

    x.value = setCharAt(str, 5, '-');

    v1 = "1";

  }

  if (len > 8 && v2 == "0") {

    var str = x.value;

    x.value = setCharAt(str, 8, '-');

    v2 = "1";

  }

}


function setCharAt(str, index, chr) {

  if (index > str.length - 1) return str;

  return str.substr(0, index) + chr + str.substr(index + 1);

}

<input type="text" oninput="myFunction()" id="vname" />


Qyouu
浏览 117回答 1
1回答

慕容3067478

我在这里写了一个更通用的答案,关于对固定大小的格式化输入使用可见掩码。如果您接受输入掩码始终可见,那应该对您有用。要使其正常工作,请将以下属性添加到您的input:<input placeholder="__-__-__-____" data-slots="_" data-accept="\w" size="13">请注意,它不会将小写字母转换为大写字母(我建议不要这样做:您不希望人们认为他们的 CAPS 锁定键出现故障)。如果这不是您希望它的工作方式(使用掩码或缺少大写),这里是专门适合您的要求的代码:const el = document.getElementById("vname"),&nbsp; &nbsp; pattern = "__-__-__-____",&nbsp; &nbsp; prev = [1, 2, 2, 4, 5, 5, 7, 8, 8, 10, 11, 12, 13],&nbsp; &nbsp; accept = /\w/g,&nbsp; &nbsp; clean = input => {&nbsp; &nbsp; &nbsp; &nbsp; input = input.match(accept) || [];&nbsp; &nbsp; &nbsp; &nbsp; return Array.from(pattern, c =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; input[0] === c || c == "_" ? input.shift() || c : c&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; },&nbsp; &nbsp; format = () => {&nbsp; &nbsp; &nbsp; &nbsp; const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i = clean(el.value.slice(0, i)).indexOf("_");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i<0? prev[prev.length-1]: back? prev[i-1] || 0: i;&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; let s = clean(el.value).join``.toUpperCase();&nbsp; &nbsp; &nbsp; &nbsp; el.value = s.slice(0, (s+"_").indexOf("_"));&nbsp; &nbsp; &nbsp; &nbsp; el.setSelectionRange(i, j);&nbsp; &nbsp; &nbsp; &nbsp; back = false;&nbsp; &nbsp; };&nbsp; &nbsp;&nbsp;let back = false;el.addEventListener("keydown", (e) => back = e.key === "Backspace");el.addEventListener("input", format);<input type="text" id="vname" />就像我提到的答案一样,这也涉及复制/粘贴(即使复制的值没有连字符)、选择、将光标放在中间、删除那里的字符等。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答