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

前端 未结 16 1598
遇见更好的自我
遇见更好的自我 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 11:47

    When we put only pattern it's not simple to check every possible date combination. Users can enter valid numbers like 99/99/9999 but it's not a valid date. Even If we limit days and months to a more restrictive value (30/31 days and 0-12 months) we still may get a case where we have leap year, febraury etc. and we cannot properly validate them using regex. So the better approach is to use a date object itself.

    let InputDate = "99/99/9999"
    let pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
    let editDate = InputDate.replace("\/","-")
    
    let dateValidation = function validation(){
      
    if(pattern.test(InputDate) && new Date(editDate) == 'Invalid Date'){
      return false;
    }else{
      return true;
    }
    
    }
    
    console.log(dateValidation()) //Return false

提交回复
热议问题