let Year = document.getElementById('year').value;
let Month = document.getElementById('month').value;
let date = document.getElementById("day").value;
if(typeof Year !== "number" || typeof Month !== "number" || typeof date !== "number"){
alert("Invalid Date ");
}
I was expecting no alert as I input numeric values, but it was still displaying the alert message in the condition.
2
Answers
The issue you’re experiencing is due to the fact that the
document.getElementById().value
method in JavaScript returns a string, not a number, even when the input field type is set to number. Therefore, when you’re checking the type ofYear
,Month
, anddate
using thetypeof
operator, it’s returning "string" instead of "number", causing the condition in yourif
statement to be true and the alert to be displayed.To resolve this issue, you need to convert the string values to numbers. You can use the
Number()
function, theparseInt()
function, or theparseFloat()
function to do this. Here’s how you can modify your code:In this modified code,
Number()
is used to convert the string values to numbers. Now, thetypeof
operator should return "number" forYear
,Month
, anddate
if numeric values are entered, and the alert should not be displayed.The value of Input is always string.
So, you can do like below.
you need more validation like
date > 0
… but my code is enough as your code now.I think my answer can help you.