skip to Main Content
          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


  1. 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 of Year, Month, and date using the typeof operator, it’s returning "string" instead of "number", causing the condition in your if 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, the parseInt() function, or the parseFloat() function to do this. Here’s how you can modify your code:

    let Year = Number(document.getElementById('year').value);
    let Month = Number(document.getElementById('month').value);
    let date = Number(document.getElementById("day").value);
    
    if(typeof Year !== "number" || typeof Month !== "number" || typeof date !== "number"){
      alert("Invalid Date ");
    }
    

    In this modified code, Number() is used to convert the string values to numbers. Now, the typeof operator should return "number" for Year, Month, and date if numeric values are entered, and the alert should not be displayed.

    Login or Signup to reply.
  2. The value of Input is always string.

    So, you can do like below.

    let Year =document.getElementById('year').value;
    let Month =document.getElementById('month').value;
    let date =document.getElementById("day").value;
    if(isNaN(Year+Month+date) ){
      alert("Invalid Date ");  
     
    }
    

    you need more validation like date > 0 … but my code is enough as your code now.

    I think my answer can help you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search