按日,月和年检查有效日期

Kar*_*arl 6 javascript date

我有三个输入,分别是日,月和年.

<div id="birthday">
    <div>
        <label for="day">Day</label>
        <input type="number" id="day" placeholder="Day" name="day" ref="day" />
    </div>
    <div>
        <label for="month">Month</label>
        <input type="number" id="month" placeholder="Month" name="month" ref="month" />
    </div>
    <div>
        <label for="year">Year</label>
        <input type="number" id="year" placeholder="Year" name="year" ref="year" />
    </div>
    <span class="clear_both"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

我想通过以下方式验证日期:

    • 年份应该有4个字符(即YYYY)
    • 年份应在1900年至今年之间.
    • 月份应在1到12之间
    • 如果年份是闰年,月份是2月(2月),那么日期应该在1到29之间
    • 如果年份不是闰年,则根据月份,日期应在1到31或1到30之间

我只能查看月份和年份:

let day = this.refs.day.value
let month = this.refs.month.value
let year = this.refs.year.value
let errors = []

if (!((year.length == 4) && (year > 1900 && year < 2016))) {
    errors.push("year");
}
if (!(month > 0 && month < 13)) {
    errors.push("month");
}
Run Code Online (Sandbox Code Playgroud)

如何在javascript中完成这项工作?请你帮助我好吗.谢谢.

小智 1

与 user3817980 类似,基于此问题但内置于您的代码中,请参见下文。

我还要检查这一天是否为负值,这可能有点过分,但没有坏处。

let day = this.refs.day.value
let month = this.refs.month.value
let year = this.refs.year.value
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
    monthLength[1] = 29;

let errors = []

if (!((year.length == 4) && (year > 1900 && year < 2016))) {
    errors.push("year");
}

if (!(month > 0 && month < 13)) {
    errors.push("month");
}

if (day < 0 || day > monthLength[month - 1]) {
    errors.push("day");
}
Run Code Online (Sandbox Code Playgroud)