Javascript Date Validation ( DD/MM/YYYY) & Age Checking

前端 未结 16 1642
遇见更好的自我
遇见更好的自我 2020-12-01 11:09

I\'ve started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.

What my HTML code includes

16条回答
  •  心在旅途
    2020-12-01 12:13

    It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)

    The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:

    function isValidDate(str) {
      var newdate = new Date();
      var yyyy = 2000 + Number(str.substr(4, 2));
      var mm = Number(str.substr(2, 2)) - 1;
      var dd = Number(str.substr(0, 2));
      newdate.setFullYear(yyyy);
      newdate.setMonth(mm);
      newdate.setDate(dd);
      return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();
    }
    console.log(isValidDate('jk'));//false
    console.log(isValidDate('290215'));//false
    console.log(isValidDate('290216'));//true
    console.log(isValidDate('292216'));//false

提交回复
热议问题