Write the code using JavaScript that validates the data entered in the username and pin fields of the form
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<form action="/">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>
<label for="pass">Password</label>
<input type="password" id="pass" name="pass" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required>
<input type="submit" value="Submit">
</form>
</div>
<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capitalLetter" class="invalid">A <b>capitalLetter (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
<script>
var myInput = document.getElementById("pass");
var letter = document.getElementById("letter");
var capitalLetter = document.getElementById("capitalLetter");
var number = document.getElementById("number");
var length = document.getElementById("length");
myInput.onfocus = function () {
document.getElementById("message").style.display = "block";
}
myInput.onblur = function () {
document.getElementById("message").style.display = "none";
}
myInput.onkeyup = function () {
var lowerCaseLetters = /[a-z]/g;
if (myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
var upperCaseLetters = /[A-Z]/g;
if (myInput.value.match(upperCaseLetters)) {
capitalLetter.classList.remove("invalid");
capitalLetter.classList.add("valid");
} else {
capitalLetter.classList.remove("valid");
capitalLetter.classList.add("invalid");
}
var numbers = /[0-9]/g;
if (myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
if (myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
</html>
Comments
Leave a comment