开发者

Javascript date of birth - prevent selecting 30 Feb etc

开发者 https://www.devze.com 2023-03-25 13:41 出处:网络
I\'m fairly inexperienced with Javascript, but I\'m trying to create this sort of protection for the registration process so that prevents the user from selecting a date that doesn\'t exist e.g. Septe

I'm fairly inexperienced with Javascript, but I'm trying to create this sort of protection for the registration process so that prevents the user from selecting a date that doesn't exist e.g. September 31 (leap years are anoth开发者_运维百科er matter for February 29 which I'll look into later).

Currently I have this, which only deals with February:

<select name="Day">
<option value="day">Day</option>
<script type="text/javascript">
function printDays(y) {
    var x = 1;
    while (x <= y) {
        document.write("<option value=" + x + ">" + x + "</option>");
        x++;
    }
}
window.onload=printDays(31);
</script>
</select>
<script type="text/javascript">
if (document.getElementById("month").value == feb) {
    printDays(28);
}
</script>

I'm sure there's something fairly obvious that's wrong here, but I'm not experienced enough to pick it out!


Answer has been accepted - although using a date selector is good idea, it does not prevent a determined user (or one with javascript disabled) returning an invalid value.

A partial solution would be to convert the value(s) input to a javascript date then back again. The datum for javascript dates is 1970 - but uses a 64-bit signed value (i.e. has a range of over 500,000 years). Note that in javascript months are numbered 0-11.

But this is not a substitute for serverside validation!


I do nut fully understand your question but consider use of http://www.nickabusey.com/jquery-date-select-boxes-plugin/ to save your work time for something else.

Demo Code


You could always use a plugin such as JQueryUI Date Picker which would handle all of the date rules for you...


Check if year, month and day combination correct

function checkDate(year, month, day) {
    try {
        var d = new Date(year, month, day);
        return !isNaN(d.getDate()) && d.getDate() == day;
    } 
    catch (e) {
        return false;
    } 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消