Javascript onchange验证使:valid和:invalid CSS选择器工作



这似乎是一件简单的事情,但我没有找到任何关于这一点。

如何使用以下内容:

// html: <input type="text" onchange="validate()">
function validate(e) {
    e.preventDefault();
    if(isValid(this.value)) {
        // make valid somehow
    } else {
        // make invalid somehow
    }
}

使下面的CSS像你期望的那样工作:

input:valid {
    background: green;
}
input:invalid {
    background: red;
}

点击"运行代码片段";看!

您可以创建一个自定义验证器,并在元素上使用setCustomValidity函数来允许使用这些选择器。

这篇文章描述了如何使用HTML5 Constraint API来实现这一点。

<标题>例子:

#inputField:valid {
  background-color: green;
}
#inputField:invalid {
  background-color: red;
}
<html>
  <body>
    Type a value (must be 'abc'): <input id="inputField">
    <script type="text/javascript">
      function validateField() {
        if (this.value !== 'abc') {
          this.setCustomValidity('Value must be abc!');
        }
        else {
          this.setCustomValidity('');
        }
      }
      window.onload = function () {
        document.getElementById("inputField").oninput= validateField;
      }
    </script>
  </body>
</html>

你在找这样的东西吗?

// html: <input type="text" onchange="validate()">
function validate(e) {
    e.preventDefault();
    var target = e.target
    if(isValid(this.value)) {
        target.classList.add("valid")
        target.classList.remove("invalid")
    } else {
        target.classList.remove("valid")
        target.classList.add("invalid")
    }
}

function validateField(event) {
  event.preventDefault();
  var target = event.currentTarget
  if (target.value != "" || target.value.length > 0) {
    target.classList.remove("invalidFunction");
    target.classList.add("validFunction");
  } else {
    target.classList.add("invalidFunction");
    target.classList.remove("validFunction");
  }
};
.invalidFunction {
  border-color: red;
}
.validFunction{
  border-color: green;
}
Field is mandatory:
<input id="inputFunctionField" onchange="validateField(event)">

如果你愿意,你可以使用css类(我添加了使用jquery添加类和删除类的语法,但也可以在纯javascript中完成).

input.valid {
  background: green;
}
input.invalid {
  background: red;
}
function validate(e) {
    e.preventDefault();   
    if(isValid(this.value)) {
       $(this).removeClass("invalid");
       $(this).addClass("valid");
    } else {
       $(this).removeClass("valid");
       $(this).addClass("invalid");
        // make invalid somehow
    }
}

none jquery(假设当前没有使用其他类)。因为这看起来像HTML,如果有额外的类,只需操作字符串来添加和删除相关的类)。

function validate(e) {
        e.preventDefault();   
        if(isValid(this.value)) {
           this.className = "valid"
        } else {
           this.className = "invalid"
            // make invalid somehow
        }
    }

最新更新