I’m trynna make a simple validation in JS by checking if the name entered has at least 5 characters and the age is over 18. This is what I have so far:
<body> <form method="POST"> <label for="name">Name: </label> <input type="text" name="name" id="name" value="John"><br> <label for="age">Age: </label> <input type="number" name="age" id="age"><br> <input type="submit" value="Submit" class="submit"> </form> <p id="demo"></p> <script> var userName = document.getElementById('name'); var userAge = document.getElementById('age'); function validationCheck(){ if (userName.length < 5){ alert("Enter a miniumum of 5 characters."); } else if (parseInt(userAge) < 18){ alert("Underaged bigot!"); } else if (userName.length < 5 && parseInt(userAge) < 18){ alert("Enter a miniumum of 5 characters you underaged bigot!") } } document.addEventListener("onclick", validationCheck()) // document.getElementById("demo").innerHTML = userAge; </script> </body>
I have no idea what am I doing wrong and why is it not working.
Advertisement
Answer
There are various issues with your code
in
if (userName.length < 5)
the variableuserName
is holding aHTMLElement
, which doesn’t have a length.Same for
else if (parseInt(userAge) < 18)
.document.addEventListener("onclick", validationCheck())
has 2 problems- the event is named
click
notonclick
- if you pass a functionname as eventhandler you must not use
()
in the end
- the event is named
Your last
else if
can never be executed, because if either one of its conditions is true, one of the first two cases will be hit and the lastelse if
won’t be evaluated. You should put that case on the top.Are you sure, want to attach your validationCheck on every click in the document? This will fire also if someone clicks on any empty place in the document or tries to focus an input with the mouse.
You should initialize the input for the age with a valid number, otherwise
parseInt(userAge.value)
will returnNaN
and the age check will fail.
<body> <form method="POST"> <label for="name">Name: </label> <input type="text" name="name" id="name" value="John"><br> <label for="age">Age: </label> <input type="number" name="age" id="age" value="0"><br> <input type="submit" value="Submit" class="submit"> </form> <p id="demo"></p> <script> var userName = document.getElementById('name'); var userAge = document.getElementById('age'); function validationCheck(){ if (userName.value.length < 5 && parseInt(userAge.value) < 18){ alert("Enter a miniumum of 5 characters you underaged bigot!") } else if (userName.value.length < 5){ alert("Enter a miniumum of 5 characters."); } else if (parseInt(userAge.value) < 18){ alert("Underaged bigot!"); } } document.addEventListener("click", validationCheck) // document.getElementById("demo").innerHTML = userAge; </script> </body>