简体   繁体   English

验证日期字段

[英]Validation Of Date Field

I have a date field on a form. 我在表单上有一个日期字段。 The date in the date field has to be after today's date and not in the past. 日期字段中的日期必须在今天的日期之后,而不是过去的日期。 It also has to be within 30 days from today's date. 还必须在今天之后的30天内。 So if today is 15/01/2013, then the form can only accept any date within 30 days after the 15/02/2013, so the 14/04/2007 plus 30 days! 因此,如果今天是2013年1月15日,那么该表格只能接受2013年2月15日之后的30天内的任何日期,因此14/04/2007加30天!

Can any please help with the correct Javascript code? 有什么可以帮助您使用正确的Javascript代码吗? I'm an amature and don't have a clue on how to achieve this. 我很老套,对如何实现这个目标一无所知。

I guess you need something like this: http://jsfiddle.net/hqNxW/1/ 我猜你需要这样的东西: http : //jsfiddle.net/hqNxW/1/

And the code... 和代码...

JavaScript 的JavaScript

var output = document.getElementById('messageOutput');
document.getElementById('validate').onclick = function () {
    var value = document.getElementById('date').value;
    if (!validateDate(value)) {
        notify('Invalid date format');
    } else {
        if (!validateDateRange(value)) {
            notify('The date should be after today but not more than 29 days!');
        } else {
            notify('Valid date');
        }
    }
}

function notify(msg) {
    output.innerHTML = msg;
}

function validateDate(date) {
    return (/^\d{2}-\d{2}-\d{4}$/).test(date);
}

function validateDateRange(inputDate) {
    var now = new Date(),
        after30Days = new Date().setDate(now.getDate() + 30)
        date = new Date(inputDate);
    return date > now && date < after30Days;
}

HTML 的HTML

<input type="text" id="date" /> <button id="validate">Validate</button>
<div id="messageOutput">Enter a date in the following format: mm-dd-yyyy</div>

Your validation function should be somthing like that: 您的验证功能应该是这样的:

function validateDateField()
{
  var result=true;        // optimistic....

  var now=new Date();
  var thisMonth=now.getMonth();
  var maxDate=new Date();
  maxDate.setMonth(thisMonth+1);

  //---------getting the user input:
  var dateStr=document.getElementById('dateField').value;

  //change "dd/mm/yyyy" format to "yyyy/mm/dd" format:
  dateStr = dateStr.replace(" ","");
  dateStr = dateStr.substr(6,4)+"/"+dateStr.substr(3,2)+"/"+dateStr.substr(0,2);

  //---------validation part:
   document.getElementById('feadBackLable').innerHTML="";
  try
  {
    var userDate=new Date(Date.parse(dateStr));
    if(userDate < now || userDate > maxDate)  
     {
           result=false;
           document.getElementById('feedBackLable').innerHTML="your date should be one of the next 30 days";
     }
  }
  catch(err)
  {
     result=false;
     document.getElementById('feadBackLable').innerHTML="please enter a valid date: dd/mm/yyyy";
  }
  //---------------------------
  return result;

} // function

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

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