Katherine Katherine -4 years ago 120
Javascript Question

Validate that multiple Prompts have a value

  1. I´m trying to write a simple test where I ask for name and age in separate Prompts. I´d like to validate user really adds a value in both prompts.
    What´s the best way to do this validation without duplicating code?
    When I click "OK" with no value, it does not ask me to add a value

    function showInfo() {
    //Asking for name in a prompt
    var name = prompt("Name: ","");
    //Checking if it is null or empty
    if (name == null || ""){alert("Please enter your name");}
    //Same for age
    var age = prompt("Age: ","");
    if (age == null || ""){alert("Please enter your age.");}

  2. Also, noticed that "null" is to check the "Cancel" button, but I was able to test that if you click "Cancel", and click "Cancel" again, it does not ask for a value. How can I solve this issue?

Answer Source

@Arshad answer adds more clarity.

on a side note, the reason why the || didn't work is the order of evaluation.

 if (age == null || "") --> evaluated as 
 if ((age == null) || "") --> true on Cancel, false on Ok

Hope this helps !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download