【问题标题】:How can I make my input border colors red when they fail validation? (Vanilla JavaScript only)当验证失败时,如何使输入边框颜色变为红色? (仅限原版 JavaScript)
【发布时间】:2021-02-20 05:30:21
【问题描述】:

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

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

我需要改变什么?

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>

【问题讨论】:

    标签: javascript html forms styles


    【解决方案1】:

    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>

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多