onlyforbopi
9/22/2018 - 7:33 AM

JS.Events.Forms.InputValidation.KeyUp

JS.Events.Forms.InputValidation.KeyUp

function validateName(evt) {
  // this is the input field text content
  var key = evt.key;  
  
  // get the output div
  var output = document.querySelector('#keyTyped');
  // display the value typed in the div 
  output.innerHTML = "Valid key: " + key;
  
  // You can do validation here, set the input field to
  // invalid is the name contains forbidden characters
  // or is too short
  // for example, let's forbid names with length < 5 chars
  if(key === "!") {
    output.innerHTML = "This key is forbidden!";
    // remove the forbodden char
    // current typed value
    var name = evt.target.value;
    // we use the substring JavaScript function
    // to remove the last character
    // first parameter = start index
    // second = last index
    evt.target.value = name.substring(0, name.length-1);
  }
}

JS.Events.Forms.InputValidation.KeyUp

A Pen by Pan Doul on CodePen.

License.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Simple input field validation using keyup events</title>
</head>
<body>
  <h1>Simple input field validation using the 'input' event</h1>
  <p>Just type a name in the input field and see what happens! <span style="color:red"> TRY TO TYPE A "!" too</span></p>
<label>
  <span>Name (required):</span>
  <input type="text" 
         name="nom" 
         maxlength="32" 
         required
         onkeyup = "validateName(event)">
</label>
  <p>
  <span id="keyTyped"></span>
</p>  
</body>
</html>