gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

Check input using HTML5 and MDL

You can use input’s attributes as min, max, pattern and so on, and then checking a simple class do what you need to. In this example we are using a Text Field component of  Material Design Lite (MDL) which shows a message and a red mark up when the value is not the right one. You could extend this with as many inputs as you like and then if all of them are correct show a login button or whatever.

JavaScript

var $input = document.querySelector("input");
var $button = document.querySelector("button");

function check() {
  if (document.querySelector(".is-invalid")) $button.classList.add("hide");
  else $button.classList.remove("hide");
}

$input.addEventListener("input", check);

HTML

<div class="demo-layout-transparent mdl-layout mdl-js-layout">
  <main class="mdl-layout__content">
    <div class="mdl-grid">
      <div class="mdl-textfield mdl-js-textfield">
        <input class="mdl-textfield__input" type="number" min="0" max="12" id="number">
        <label class="mdl-textfield__label" for="number">Number between 0 and 12...</label>
        <span class="mdl-textfield__error">Input is not a number between 0 and 12!</span>
      </div>
      <button class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect">ok</button>
    </div>
  </main>
</div>

CSS

.hide {
  display: none;
}
Open in JSFiddle

Note that in old browsers and android versions before Lolipop where the Web View isn’t Chrome you will need to use directly Validation DOM Methods. Ex:

document.querySelector('input').validity.rangeOverflow

Be careful because even some Validation DOM Methods are not well supported in old browsers versions.

Tags: DOM, input, Material, MDL, validation