Tuesday, May 26, 2009

Validate text to match specific date pattern on JavaScript

My team got requirement to standarize date appearance to dd-MMM-yyyy, thanks to ASP.Net Ajax who has CalendarExtender tools so we may manipulate the way date format returned.

Unfortunately, we also allow user to free type value of date on any datetime control we have provided, which causing us a problem on how to restrict it to expected format. CustomValidator come in handy as its has capability to validate thru JavaScript, so next problem is how to build a javascript code to validate its format to be dd-MMM-yyyy, as we need a handy script and fight with deadline, so below code is written:

function isDate(sDate) {
var datePat = /^(\d{1,2})(\/|-)(\w{3})(\/|-)(\d{4})$/;
var matchArray = sDate.match(datePat); // is the format ok?

if(matchArray==null) return false;

return true;
}


Above code only validated date written format as per expected pattern, it won't check validity of data value entered, for instance if you type: 45-Apr-2009, script will return true, so that problem stil a homework for our team :)

No comments:

Post a Comment