Javascript - 需要日期验证 IF 语句

Javascript - Date Validation IF Statement needed

本文关键字:验证 IF 语句 日期 Javascript      更新时间:2023-09-26

所以我已经写了练习的这一部分,但我需要一个使用 "Date" 和 "dateOfBirth.getFullYear() == year" 等对象的 IF 语句来验证用户是否输入了正确的日期。一个简单的解决方案将不胜感激。我如何在其中放置一个 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();
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/