Could someone explain why this code behaves incorrectly. My aim to to have a form that suppresses the submission if the name is not entered, or if a non signed integer is inputted for the age. I have logged the isInteger and more than zero comparisons and they both appear false so I cannot understand why the 'alert("Please enter a valid age.");' is not being executed in the OR statement.
I hope I haven't missed something obvious as I have trying to debug this for an hour now.
Any help would be appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Practice</title>
<meta charset="utf-8">
<style>
input {
display: block;
margin-bottom: 1em;
}
label {
float: left;
width: 5em;
padding-right: 1em;
text-align: right;
}
#submit {
margin-left: 7em;
}
</style>
<script>
function validateForm() {
if (document.forms[0].userName.value == "") {
alert("Name field cannot be empty.");
return false;
}
console.log(Number.isInteger(document.forms[0].userAge.value));
console.log(document.forms[0].userAge.value < 0;
if (!Number.isInteger(document.forms[0].userAge.value) ||
document.forms[0].userAge.value < 0) {
alert("Please enter a valid age.");
return false;
}
if (document.forms[0].userAge.value < 18) {
alert("Age is less than 18. You are not an adult.");
return false;
} // end if
alert("Name and Age are valid.");
return true;
} // end function validateForm
</script>
</head>
<body>
<h1>JavaScript Form Handling</h1>
<form method="post" action="http://webdevbasics.net/scripts/demo.php" onsubmit="return validateForm();">
<label for="userName">Name:</label>
<input type="text" name="userName" id="userName">
<label for="userAge">Age:</label>
<input type="text" name="userAge" id="userAge">
<input type="submit" value="Send information" id="submit">
</form>
</body>
</html>