首页 > 解决方案 > 使用 JavaScript RegEx 验证输入

问题描述

我有这个 JS 函数来验证用户输入并确保它是 2000-2021 之间的一年,它工作得很好,问题是当我写无效输入时它会将轮廓更改为红色,但是当我写一个有效输入时它仍然存在红色的。即使我从一开始就写了有效的输入,它也会变红。

var  batchRegex=/^[2][0][0-2][0-1]$/;
function checkBatch(batch){
if (batch = ""){
  document.getElementById('batch').style.outlineColor = "red";
}
else if(!batchRegex.test(batch)){
  document.getElementById('batch').style.outlineColor = "red";
}
else if(batchRegex.test(batch)){
  document.getElementById('batch').style.outlineColor = "none";
}
}
<form method="post">
  <input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this.value)" required>
  <input type="submit" name="submit">
  </form>

标签: javascriptregexvalidationdom

解决方案


您的代码中有多个问题:

  1. if (batch = ""){应该if (batch == ""){

  2. 正则表达式/^[2][0][0-2][0-1]$/仅匹配值:

    2000, 2001, 2010, 2011, 2020,2021

但您想匹配 和 之间的所有20002021

为什么不尝试这样简单的事情:

function checkBatch(batch){
  if (batch.value >= 2000 && batch.value <= 2021){
    batch.style.outlineColor = "green";
  } else {
    batch.style.outlineColor = "red";
  }
}
<form method="post">
  <input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
  <input type="submit" name="submit">
  </form>

而不是通过javascript更改内联样式,只需添加一个类,然后您可以使用CSS更改样式,例如..

function checkBatch(batch){
  if (batch.value >= 2000 && batch.value <= 2021){
    batch.classList.remove('alert')
    batch.classList.add('success')
  } else {
    batch.classList.remove('success')
    batch.classList.add('alert')
  }
}
input.alert {
  outline-color: red;
}
input.success {
  outline-color: green;
}
<form method="post">
  <input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
  <input type="submit" name="submit">
  </form>


推荐阅读