我有三个输入,分别是日,月和年.
<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)
我想通过以下方式验证日期:
年
月
天
我只能查看月份和年份:
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)