html - Javascript onchange validation so that :valid and :invalid CSS selectors work -
this seems simple thing do, have not been able find this.
how can use following:
// html: <input type="text" onchange="validate()"> function validate(e) { e.preventdefault(); if(isvalid(this.value)) { // make valid somehow } else { // make invalid somehow } }
so following css works might expect:
input:valid { background: green; } input:invalid { background: red; }
click "run code snippet" see!
you can create custom validator , use setcustomvalidity
function on element allow use of these selectors.
this article describes how use html5 constraint api achieve this.
example:
#inputfield:valid { background-color: green; } #inputfield:invalid { background-color: red; }
<html> <body> type value (must 'abc'): <input id="inputfield"> <button>check it!</button> <script type="text/javascript"> function validatefield() { if (this.value !== 'abc') { this.setcustomvalidity('value must abc!'); } else { this.setcustomvalidity(''); } } window.onload = function () { document.getelementbyid("inputfield").onchange = validatefield; } </script> </body> </html>
Comments
Post a Comment