dimanche 26 mars 2017

Age calculator: checking for a blank input or a string input

I have a function that asks you questions to determine your age. I want to cancel the function and issue an alert if the user enters a string value or doesn't enter anything at all.

Here's my code so far:

<button id="btn"> Calculate Age </button>

<p id="para"></p>


document.getElementById("btn").addEventListener("click", ageCalc);


function ageCalc () {

    // Calculate year of birth

    var year = prompt("What year were you born?");
    if (parseInt(year) < 1917) {
        return alert("Please enter a valid year");
    }

    // Calculate month of birth

    var month = prompt("Numerically, what month were you born?");

    if (parseInt(month) > 12 || parseInt(month) < 1 ) {
        return alert("Please enter a valid month!");
    }


    // Calculate day of birth

    var day = prompt("What day were you born?");

    if(parseInt(day) > 32 || parseInt(day) < 1) {
        return alert("Please enter a valid day!");
    }

    // Calculate age based on user input

    var presentDate = new Date ();
    var birthDate = new Date(year,month,day);
    var age = (presentDate - birthDate) / 1000 / 60 / 60 / 24 / 365;

    return document.getElementById("para").innerHTML = "You are " + Math.floor(age) + " years old.";
}

What is the proper move here? I assume it will be tweaking the if statement somehow to check for strings or blank statements but i'm kinda lost. Any thoughts guys?

Aucun commentaire:

Enregistrer un commentaire