views:

92

answers:

5

Using javascript I need to validate a form field containing a date in the format: 21/04/2010. The date must be a weekday. Is it possible to create a regular expression for this or is there another, better way to do it?

+3  A: 

Javascript has a date class. See http://www.w3schools.com/jsref/jsref_obj_date.asp

What you will need to do is create your Date object:

date = new Date(2010, 5, 19); //Year, month, day

Note the month is zero indexed, so subtract by 1. This is June

Then get the day:

day = date.getDay(); //Day is also 0 indexed.

var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.write("Today is " + weekday[date.getDay()]);
Keyo
+6  A: 

Regex is clearly the wrong tool. Use Date.getDay():

var d = new Date();
var parts = dateStr.split("/");
// Date of month is 0-indexed.
var d = new Date(parts[2], parts[1] - 1, parts[0]);
var day = d.getDay();
if(day == 0 || day == 6)
{
  // weekend
}
Matthew Flaschen
Of course, I should have realised that. Thanks.
dannybolabo
+4  A: 

Use getDay() which returns an integer from 0-6 where 0 is Sunday, and 6 is Saturday.

If the value is 1-5, then it's a weekday.

0 or 6 means it's a weekend.

Anurag
A: 

The simple answer is NO. Use Date.getDay() since it is made for precisely that purpose.

D.Shawley
+1  A: 

The Javascript Date.parse function is only specified to used IETF standard time (e.g. "Aug 9, 1995"), so is not suited to your requirement. For 21/04/2010 you'll need to split it yourself and use the Date constructor to assemble a date. It would probably be safer to use something tried and tested. Have you looked at datejs?

spender