Patrick Michaud
Patrick Michaud

Reputation: 3

Date restrictions on user input in JavaScript

I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:

if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)

The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.

Upvotes: 0

Views: 56

Answers (2)

Steve Wakeford
Steve Wakeford

Reputation: 331

Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.

var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);

Upvotes: 1

Amonn
Amonn

Reputation: 84

If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:

    var momentdate = moment(date);
    if (momentdate.isAfter(momentdate.add(1, 'year') ||
     momentdate.isBefore(momentdate.startOf('day')) {
      // Invalid date?
    }

Hope this helps.

Upvotes: 0

Related Questions