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
2010-08-04 01:17:33
+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
2010-08-04 01:20:46
Of course, I should have realised that. Thanks.
dannybolabo
2010-08-04 01:58:38
A:
The simple answer is NO. Use Date.getDay()
since it is made for precisely that purpose.
D.Shawley
2010-08-04 01:22:31
+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
2010-08-04 01:23:11