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);
}
}
<!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>
HTML.CSS.JS.FetchingServersideData.JS.ex1
-----------------------------------------
A [Pen](https://codepen.io/Onlyforbopi/pen/NLQeMy) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).
[License](https://codepen.io/Onlyforbopi/pen/NLQeMy/license).