Javascript - 日期验证需要IF语句

时间:2015-03-08 08:39:47

标签: javascript

所以我已经写了这个练习的一部分,但我需要一个IF语句,使用“Date”和“dateOfBirth.getFullYear()== year”之类的对象来验证用户输入了正确的日期。非常感谢一个简单的解决方案。我如何在其中放入一个IF语句来测试用户输入的生日是否正确,如果错误则会拒绝?

//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();

1 个答案:

答案 0 :(得分:1)

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/(例如,您应输入2014-02-02

或者,您可以递归地执行此操作:

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