简体   繁体   English

JavaScript表单验证,检查日期是否已过

[英]Javascript form validation, check if date is passed

I'm trying to validate a form here and I'm almost done. 我正在尝试在此处验证表单,我差不多完成了。 The only issue is I can't figure out a way of validating the dates field to check whether the date that has been put in hasn't passed. 唯一的问题是我无法找出一种验证日期字段来检查是否已通过的日期尚未通过的方法。 It has to be done through Javascript... btw, here is the HTML: 必须通过Javascript完成... btw,这是HTML:

<label for="reservationDate">Date of reservation (DD/MM/YYYY):</label>

<input type="text" id="date" name="date" onblur="validateDate(date)">

<span id="dateError" style="display: none;">Please enter your date of reservation in this format DD/MM/YYYY</span>

Here is the Javascript: 这是Javascript:

function validateDate(x) {
   var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
   if(re.test(document.getElementById(x).value)){ 
        document.getElementById(x).style.background ='#ccffcc'; 
        document.getElementById(x + 'Error').style.display = "none"; 
        return true;
   } else{ 
        document.getElementById(x).style.background ='#e35152'; 
        document.getElementById(x + 'Error').style.display = "block"; 
        return false; 
   }
}

Hope someone can help :) 希望有人可以帮助:)

Here's some code to make this a specific answer to suit your needs: 下面是一些代码,可以根据您的需要做出特定的答复:

function validateDate(x) {
   var re = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/;
   var entered = new Date(document.getElementById(x).value);
   var today = new Date();
   if( entered > today ) {
        document.getElementById(x).style.background ='#ccffcc'; 
        document.getElementById(x + 'Error').style.display = "none"; 
        return true;
   } else{ 
        document.getElementById(x).style.background ='#e35152'; 
        document.getElementById(x + 'Error').style.display = "block"; 
        return false; 
   }
}

Here is the working, tested code: http://jsfiddle.net/digitalextremist/rwhhg/1/ 这是经过测试的有效代码: http : //jsfiddle.net/digitalextremist/rwhhg/1/

Some past answers which are pieces but not really the whole deal: 过去的一些答案是零散的,但不是全部:

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

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