Validate date for anyone over 18 with jQuery

前端 未结 6 2116
借酒劲吻你
借酒劲吻你 2021-01-18 03:07

I have a form on my site that should validate for anyone who is over 18.

var day = $(\"#dobDay\").val();
var month = $(\"#dobMonth\").val();
var year = $(\"         


        
6条回答
  •  梦谈多话
    2021-01-18 03:53

    Here is a somewhat lighter version that I tested:

    var day = 1;
    var month = 1;
    var year = 1999;
    var age = 18;
    
    var cutOffDate = new Date(year + age, month, day);
    
    if (cutOffDate > Date.now()) {
        $('output').val("Get Outta Here!");
    } else {
        $('output').val("Works for me!");
    }
    

    The key is to add the minimum age to the birthdate and confirm that it is before the current date. You are checking if the current date minus the minimum age (basically the latest birthdate allowed) was greater than than the birthdate provided, which will give you the reverse.

提交回复
热议问题