首页 > 解决方案 > 当验证失败时,如何使输入边框颜色变为红色?(仅限原版 JavaScript)

问题描述

所以我在表单上有一些文本输入,当用户尝试提交表单并且输入不符合特定标准时,我想让边框变成红色。标准是字段不能为空,如果是,表单会将用户带回该字段并显示红色边框。

以下是我到目前为止所得到的,但不仅样式没有显示,而且字段也消失了。

我需要改变什么?

const submitButton = document.getElementById('submitButton');
const name = document.getElementById('name');
const email = document.getElementById('email');

function nameValidation() {
    if (name.value == 0) {
        name.style.borderColor = "red solid 5px";
    }
}

function emailValidation() {
    if (email.value == 0) {
        email.style.borderColor = "red solid 5px";
    }
}

submitButton.addEventListener('click', () => {
    nameValidation();
    emailValidation();
});
<form action="index.html" novalidate>
      <fieldset>
      
        <label for="name">Name:</label>
          <input type="text" id="name">

        <label for="mail">Email:</label>
          <input type="email" id="email">
          
      </fieldset>
      
      <button id="submitButton">Register</button>
</form>

标签: javascripthtmlformsstyles

解决方案


HTML 按钮具有默认行为,因此它会刷新整个页面,这就是您的表单消失的原因。为了防止这种情况,您只需要像我在下面的提交按钮事件处理函数中所做的那样使用event.preventDefault() 。

其次,您的 CSS 不适用的原因是您试图将 '5px solid' 添加到border-color CSS 属性。边框颜色只接受颜色作为输入。如果您需要设置其他属性,则需要在边框上进行。

此外,您将 name.value 和 email.value 的值与 0 进行比较。您应该使用空字符串 '' 来代替。然而,空字符串在 Javascript 中是一个假值,所以即使你只是说 name.value 并且 value 是空字符串 (''),那么它在 if 条件下也会是假的。您需要做的就是if(!name.value),即如果 name.value 不为真,则执行条件。

const submitButton = document.getElementById('submitButton');
const name = document.querySelector('#name');
const email = document.querySelector('#email');

function nameValidation() {
  if (!name.value) {
    name.style.border = '5px solid';
    name.style.borderColor = 'red';
  }
}

function emailValidation() {
  if (!email.value) {
    email.style.border = '5px solid';
    email.style.borderColor = 'red';
  }
}

submitButton.addEventListener('click', e => {
  e.preventDefault();
  nameValidation();
  emailValidation();
});
<form action="index.html" novalidate>
          <fieldset>
            <label for="name">Name:</label>
            <input type="text" id="name" />

            <label for="mail">Email:</label>
            <input type="email" id="email" />
          </fieldset>

          <button id="submitButton">Register</button>
        </form>


推荐阅读