html 如何在表单中实现这个正则表达式来验证数字?

jtoj6r0c  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(112)

如果输入的确切数字为300000,则表单将被提交。任何其他小于或大于300000的值都将导致显示错误消息。错误消息应仅在值小于300000时显示。代码中的错误是什么?

document.addEventListener("DOMContentLoaded", function() {
  document.querySelector('#sbutton').addEventListener('click', function(event) {
    event.preventDefault();
    let inputV = document.querySelector('#budget').value.trim();
    let budgetRegex = /^3[0-9]{5,}/;
    const errorMessage = document.querySelector('#errormsg');
    let form = document.querySelector("form");
    if (inputV == "" || !budgetRegex.test(inputV)) {
      errorMessage.innerHTML = "Value should be at least 300,000.";
      errorMessage.style.display = 'block';
    } else {
      errorMessage.innerHTML = "";
      errorMessage.style.display = 'none';
      form.submit();
    }
  });
});
<form action="https://dragonmm.xyz" method="post">
  <div class="contact-box">
    <div class="left1"></div>
    <div class="right1">
      <h2>Start</h2>
      <label for="name"></label>
      <input id="name" type="text" class="field" placeholder="Name" required>

      <label for="email"></label>
      <input id="email" type="text" class="field" placeholder="Email" required>

      <label for="phone"></label>
      <input id="phone" type="text" class="field" placeholder="Phone" required>

      <label for="budget"></label>
      <input id="budget" type="text" name="budget" class="field budgetInput" placeholder="Budget" required>
      <div id="errormsg"></div>
    </div>
  </div>
  <button type="submit" value="Send" class="btn1" id="sbutton">Send</button>
</form>
yr9zkbsy

yr9zkbsy1#

使用数字输入字段(type="number")。使用字段的min属性来限制输入(尽管用户仍然可以输入自己的文本)。接下来,将值转换为Number,以便进行计算。
下面是一个最小的示例,使用event delegation
最后:您也应该始终检查服务器端的值。

document.addEventListener(`input`, handle);

function handle(evt) {
  if (evt.target.id === "budget") {
    if (+evt.target.value < +evt.target.min) {
    //  ^convert to Number
      return document.querySelector(`#budgetError`)
        .classList.remove(`hidden`);
    }
    return document.querySelector(`#budgetError`)
        .classList.add(`hidden`);
  }
}
#budgetError {
  color: red;
}

.hidden {
  display: none;
}
<input id="budget" type="number" min="300000"> budget
<div id="budgetError" class="hidden">
  Not enough! We need at least 300,000</div>

相关问题