John Smith
John Smith

Reputation: 57

Javascript - Date Validation IF Statement needed

So i wrote this part of an exercise already, but i need an IF statement using objects like "Date" and "dateOfBirth.getFullYear() == year" to validate that the user has entered a correct date. A simple solution would be very much appreciated. How do i put an IF statement in that will test if the user entered birthday is correct, and will reject if its false?

//Date Validation
var canvas;
canvas = openGraphics();

var phrase1;
phrase1 = "Name: ";

var name;
name = prompt( "Please enter your name:" );

var phrase2;
phrase2 = "<br />Mobile Number: ";

var mobile;
mobile = prompt( "Please enter your mobile number:" );

var phrase3;
phrase3 = "<br />E-mail Address: ";

var email;
email = prompt( "Please enter your E-mail Address:" );

var date;
date = prompt( "What day were you born on? e.g. 21st");
date = parseInt(date, 10);

var phrase4 = "<br /> Date of Birth: ";

var month;
month = prompt( "What month were you born in? e.g. April");

var phrase5 = " ";

var year;
year = prompt( "What year were you born in? e.g. 1996");

var phrase6 = " ";

var age;
var a = 2014;
var b = year;

age = a - b;

var phrase7 = "<br />Approximate Age: ";

var message;

message = phrase1 + name + phrase2 + mobile + phrase3 + email + phrase4 +        date + phrase5 + month + phrase6 + year + phrase7 + age;


canvas.drawString(message, 10, 10 );
canvas.setFont( "calibri", "16px", Font.ITALIC );
canvas.paint();

Upvotes: 0

Views: 63

Answers (1)

Anatoliy Arkhipov
Anatoliy Arkhipov

Reputation: 691

function checkDate(date) {
   return new Date(date).getFullYear() == 2014
}

var date = null

while( ! checkDate(date)) {
    date = prompt('Please enter a date')
}

alert('Success, your date is: ' + date)

http://jsfiddle.net/uvfxwkzo/1/ (You should enter 2014-02-02, for example)

Or, you can do it recursively:

http://jsfiddle.net/uvfxwkzo/2/

Upvotes: 1

Related Questions