Suman Ghosh
Suman Ghosh

Reputation: 13

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. 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!

Can any please help with the correct Javascript code? I'm an amature and don't have a clue on how to achieve this.

Upvotes: 0

Views: 9737

Answers (2)

yoav barnea
yoav barnea

Reputation: 5994

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

Upvotes: 0

Minko Gechev
Minko Gechev

Reputation: 25672

I guess you need something like this: http://jsfiddle.net/hqNxW/1/

And the code...

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

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

Upvotes: 1

Related Questions