简体   繁体   English

检查出生日期

[英]Checking date of birth

I know the subject exists on StackOverFlow as below, but I don't understand.我知道该主题存在于 StackOverFlow 上,如下所示,但我不明白。

How to validate date with format "mm/dd/yyyy" in JavaScript? 如何在 JavaScript 中使用“mm/dd/yyyy”格式验证日期?

My goal is that when the date of birth is false, an error message appears.我的目标是,当出生日期为假时,会出现一条错误消息。

I want to understand how to valide the year for example?例如,我想了解如何验证年份?

If the user enters 1000-01-01 or 3000-01-01, I would like to get an error message.如果用户输入 1000-01-01 或 3000-01-01,我想收到一条错误消息。

Thank you for your help谢谢您的帮助

 function validation(){ var dateofbirth = document.getElementById('dateofbirth').value; if(dateofbirth == ""){ document.getElementById('dateofbirthError').innerHTML = "Empty"; return false; } }
 <form action="#" onsubmit="return isValidDate()" > <label>Date of birth: </label> <br> <input type="date" name="dateofbirth" id="dateofbirth"> <br> <span id="dateofbirthError"></span> <br> <input type="submit" value="ok"> </form>

we can use customized function or date pattern.我们可以使用定制的 function 或日期模式。 Below code is customized function as per your requirement please change it.下面的代码是定制的 function 根据您的要求请更改它。

     function validation(){

    var dateofbirth = document.getElementById('dateofbirth').value; 

            if(!isValidDate(dateofbirth)){
                document.getElementById('dateofbirthError').innerHTML = "Empty";
                console.log("Invalid date")
                return false;
            }
  function isValidDate(str) {
    var getvalue = str.split('-');
    var day = getvalue[2];
    var month = getvalue[1];
    var year = getvalue[0];
    if(year < 1900 || year > 2100){
    return false;
    }
    if (month < 1 || month > 12) { 
      return false;
     }
     if (day < 1 &|| day > 31) {
      return false;
     }
     if ((month==4 || month==6 || month==9 || month==11) && day==31) {
      return false;
     }
     if (month == 2) { // check for february 29th
      var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
      if (day>29 || (day==29 && !isleap)) {
       return false;
     }
     }
     else{
     return true;

     }
    }      

Here's how you can do this by leveraging html5 constraints .以下是如何利用html5 约束来做到这一点。 This has a dual effect of already displaying error messages when the user tries to submit, as well as preventing submission while the form is invalid.这具有双重效果,即在用户尝试提交时已经显示错误消息,以及在表单无效时阻止提交。

In this case, I also set it up so that it displays an error message whenever the form gets set to an invalid state (rather than waiting for submission).在这种情况下,我还对其进行了设置,以便在表单设置为无效的 state(而不是等待提交)时显示错误消息。

 function onSubmit(event) { event.preventDefault(); console.log(event.target.dateofbirth.value); } function onInvalid(event) { document.getElementById('dateofbirthError').innerHTML = event.target.validationMessage; } // You can make this only trigger on blur to make it not try and give warnings while they are editing. // Or you can remove the checkValidity calls from here // to make it so the warnings only show up when the user presses enter function validation(event) { const { currentTarget: target } = event; const dateofbirth = target.value; if (dateofbirth == "") { // This will change the error message from 'Please fill out this field' to 'Empty' //target.setCustomValidity('Empty') target.checkValidity() return false; } const [year, month, day] = dateofbirth.split('-').map(val => +val); const currentYear = new Date().getFullYear(); if (year > currentYear || year <= currentYear - 150) { target.setCustomValidity('Not a real birthday.') target;checkValidity() return. } target.setCustomValidity('') if (target.checkValidity()) { // Clear the displayed errors as invalid is not called if there are no errors. document.getElementById('dateofbirthError').innerHTML = '' } }
 .error { color: red; }
 <form action="#" onsubmit="onSubmit(event)"> <label>Date of birth: </label> <br> <input type="date" name="dateofbirth" id="dateofbirth" onInput="validation(event)" onBlur="validation(event)" onInvalid="onInvalid(event)" required> <br> <span id="dateofbirthError" class="error"></span> <br> <input type="submit" value="ok"> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM