puks1978
puks1978

Reputation: 3697

jquery validate date field must be future

I have a method

$.validator.addMethod("dateDDMMYYYY",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-2])[.,/ -](0?[1-9]|1[0-2])[.,/ -](19|20)?\d{2}$/);
    },
    "* Please enter a valid date (dd/mm/yyyy)"
);

to check if a date entered is a valid dd/mm/yyyy date but I would like to modify (or create a new method) to check that the date entered is in the future and also check how far in the future.

For example I would like to show a message if the date entered is less than 2 days in the future but don't show the message if the date is greater than 2 days in the future.

Thanks in advance

Upvotes: 0

Views: 1721

Answers (2)

Dave Ward
Dave Ward

Reputation: 60580

Once you're certain it's a valid date, you could parse it and compare that with the current date:

// Assuming value is the date string.
var date = new Date(value);

// Create a new date, stripping the time away.
var today = new Date(new Date().toDateString());

// Subtracting one date from another gives you the number
//  of milliseconds between the two. Divide that down to days.
var daysInTheFuture = (date - today) / 1000 / 60 / 60 / 24;

Upvotes: 1

Lyn Headley
Lyn Headley

Reputation: 11588

the duration of two days in milliseconds is:

var twoDays = 2 * 24 * 60 * 60 * 1000

So you can create a date two days in the future like so:

var now = new Date()
var future = new Date(now.getTime() + twoDays)

Javascript also has a Date constructor like so:

new Date(year, month [, day, hour, minute, second, millisecond]);

So just extract the entered date using your regex (I'll let you do that)

var year = ...
var month = ...
var day = ...

var entered = new Date(year, month, day)

Then your test is:

entered - now > twoDays

if that expression is true, they have entered a date more than two days in the future.

Upvotes: 0

Related Questions