Date Validation via Regular Expression

June 29, 2007

The function takes an input string and an optional format string. The format string is only 3 characters long and determines the relative positions of the month, day, and year. If the format string is omitted, then it will be “MDY” (month first, then day, then year). There are three different types of dividers that can be used in the date string. These are the slash (/), the period (.) and the dash (-). Years can be either 2 digits (00-49 are assumed to be 21st century and 50-99 are assumed to be 20th century) or 4 digits.

The way the regular expression part of the function works is by using the “remember” capabilities of regular expressions. This assures that the same divider is used in both positions. (In other words, you couldn’t do MM/DD-YYYY). The “\1” in the regular expression says “use the same thing you used in parentheses before (which is the check for a slash, period, or dash) and apply the check here”.

If the string passes the regular expression (there are 2 checks since the year can be either 2 or 4 digits), then additional JavaScript is performed to check the validity of the date. Instead of doing all the checks for the day of the month being out of range and checking for leap years, a simple approach is taken. A new date object is created in JavaScript. If the numbers are out of range (like February 31), JavaScript will still create an object, it will just be adjusted to be a valid date. So create the date and then check to see if it was adjusted by JavaScript. If it was adjusted, then the original date is not a valid date.

function isValidDate(dateStr, format)

//check if 2nd parameter contains valid value or not
//if not valid then set default format = “MDY”

if (format == null) { format = “MDY” }
format = format.toUpperCase();
if (format.length != 3) { format = “MDY” }
if ( (format.indexOf(“M”) == -1) ||
(format.indexOf(“D”) == -1) ||
(format.indexOf(“Y”) == -1)
{ format = “MDY” }

if (format.substring(0, 1) == “Y”)
{ // If the year is first
var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
else if (format.substring(1, 2) == “Y”)
{ // If the year is second
var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
{ // The year must be third
var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

// If it doesn’t conform to the right format
//(with either a 2 digit year or 4 digit year), fail

if ( (reg1.test(dateStr) == false) &&
(reg2.test(dateStr) == false)
{ return false; }

// Split into 3 parts based on what the divider was
var parts = dateStr.split(RegExp.$1);

// Check to see if the 3 parts end up making a valid date
//extract month part

if (format.substring(0, 1) == “M”) { var mm = parts[0]; }
else if (format.substring(1, 2) == “M”) { var mm = parts[1]; }
else { var mm = parts[2]; }

//extract day part
if (format.substring(0, 1) == “D”) { var dd = parts[0]; }
else if (format.substring(1, 2) == “D”) { var dd = parts[1]; }
else { var dd = parts[2]; }

//extract Year part
if (format.substring(0, 1) == “Y”) { var yy = parts[0]; }
else if (format.substring(1, 2) == “Y”) { var yy = parts[1]; }
else { var yy = parts[2]; }

//if year is in 2 digit
//00-49 are assumed to be 21st century and 50-99 are assumed to be 20th century
if (parseFloat(yy) <= 50)
{ yy = (parseFloat(yy) + 2000).toString(); }
if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }

var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);

if (parseFloat(dd) != dt.getDate()) { return false; }

if (parseFloat(mm)-1 != dt.getMonth()) { return false; }

return true;


The function returns true if the date is valid and false if it is not. So, your validation could look something like:

if (!isValidDate(myDateString, “DMY”)) { alert(“The date is not in the correct format.”); }

Breaking Par Consulting Inc.

happy programming!!!

Frequently Used Regular Expressions

June 28, 2007

There are a variety of tasks that regular expressions can be used for in regards to input validation and file parsing. Some of the most common expressions are often hard to remember because of the power and options available. Here is a list of commonly used regular expressions:

Use Expression
Social Security Number \d{3}-\d{2}-\d{4}
US Phone Number ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
US Postal Code \d{5}(-\d{4})?
Internet EMail Address [\w-]+@([\w-]+\.)+[\w-]+
Internet URL http://(%5B\w-]\.)+[\w-](/[\w- ./?%=]*)?
Simple Password (digit) ^(?=.*\d).{4,8}$
Advanced Password (upper, lower, digit) ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$
Common File masks ^(.+)\\(.+)\.(.+)
Major Credit Card \d{4}-?\d{4}-?\d{4}-?\d{4}

ASP alliance

Password Validation via Regular Expression

June 26, 2007

I have recently been working on Password validation via regular expression, after so many researches I came across very good quality articles so I recapitulate over here.

When it comes to password validation using regular expressions, things can get a bit complicated. Normally, you want people to enter a “good” password that has a mix of numbers and letters. But you may not care where the numbers and letters appear. So you’re not looking for a “pattern” in the string. You just want a letter somewhere and a number somewhere.

In this first example, the password must be at least 8 characters long and start and end with a letter.


The ^ looks for something at the start of the string. The brackets indicate the valid character set. So it must start with an upper or lower case letter. After that, the \w means there can be valid alphanumeric characters (numbers 0-9, upper/lower case letters a-z, the underscore) and says there must be at least 6 (but no upper limit). Then comes another set and the $ looks for something at the end of the string. So this statement says there must be a letter, then at least 6 of any alphanumeric characters, then a letter (making 8 the minimum number of characters).

In this second example, the password length doesn’t matter, but the password must contain at least 1 number, at least 1 lower case letter, and at least 1 upper case letter.


Again, the ^ and $ are looking for things at the start and end. The “\w*” combination is used at both the start and the end. \w means any alphanumeric character, and * means zero or more. You’ll see why it’s “zero or more” in a bit. Between are groupings in parentheses. The “(?” combination is a flag in regular expressions. Basically, they say “apply the following formula, but don’t consume any of the string”. In this example, instead of specifying the order that things should appear, it’s saying that it must appear but we’re not worried about the order.

The first grouping (called an “atom” in “regular expresion speak”) uses the = sign. This means that there must be a match. Other choices are ! for a negative match (the string must not look like this). There are others (more complicated) for preceeding matches and stuff. We can refer you to a regular expression syntax web site for further details.

After the = sign comes “\w*\d”. Again, any alphanumeric character can happen zero or more times, then any digit (\d means any digit from 0 to 9) can happen. So this checks to see if there is at least one number in the string. But since the string isn’t comsumed, that one digit can appear anywhere in the string.

The next atom (grouping) is (?=\w*[a-z]). This is similar to the digit grouping, except it looks for a lower case letter. Again, the lower case letter can appear anywhere, but there has to be at least one.

The third atom is (?=\w*[A-Z]) which looks for an upper case letter somewhere in the string.

At the end is zero or more alphanumeric characters. To match this string, the minimum characters needed is 3 (one upper case letter, one lower case letter, and one number).

In this third example:

  • Must be at least 10 characters
  • Must contain at least one one lower case letter, one upper case letter, one digit and one special character
  • Valid special characters are –   @#$%^&+=


As you can see in the regex, the list of special characters is configurable.

Breaking Par Consulting
Anil John’s Blog

VS 2008 JavaScript Intellisense

June 22, 2007

One of the features that web developers will really like with VS 2008 is its built-in support for JavaScript intellisense.  This is enabled in both the free Visual Web Developer 2008 Express edition as well as in Visual Studio, and makes using JavaScript and building AJAX applications significantly easier. 

Below link is a quick tour of some of the new JavaScript intellisense features to take advantage of:
Scott Gu’s Blog

ViewState improvements in ASP.NET 2.0

June 18, 2007

When I browsing through Internet I came across very good article : View State improvement made in .NET 2.0.

In this article is not going to expol the benefits of view state. this article will explain you whats improved for ViewState in .NET 2.0.

Couple of things to keep in mind: Turn off view state when its not needed and secondly ask yourself if its cheaper to requery the database or cache the queried data and data-bind on each request instead of using view state (data controls by their very nature generate significant view state).

Control State

One of the most frustrating aspects of working with server-side controls in ASP.NET 1.x is the all-or-nothing mentality with respect to view state. Behavioral aspects of controls like pagination in the DataGrid or selection change notifications in textboxes require view state to be enabled to function properly. I’m sure all of you are sufficiently daunted by the prospect of leaving view state enabled in any of your DataGrids at this point. In ASP.NET 2.0, Microsoft addresses this particular problem by partitioning the view state into two separate and distinct categories: view state and control state.

Control state is another type of hidden state reserved exclusively for controls to maintain their core behavioral functionality (SelectedIndex in a ListBox is an essential bit of information), whereas view state only contains state to maintain the control’s contents (UI). Technically, control state is stored in the same hidden field(__VIEWSTATE) as view state (being just another leaf node at the end of the view state hierarchy), but if you disable view state on a particular control, or on an entire page, the control state is still propagated. Control state allows a control to intelligently split their state into what is absolutely required and what is not. The nice aspect of this implementation is that we can now amend our original principle on optimizing view state for ASP.NET 2.0 to be much stronger: if you populate the contents of a control every time a page is requested, you should disable view state for that control.

As long as control builders properly partition their state into behavioral state (to maintain core functionality) and UI state (to retain contents), this statement should be followed religiously. I would like to tell you to start following this recommendation now with all work done in ASP.NET 2.0, but the DataGrid has not been refactored to keep its behavioral state in control state. Fortunately, the new GridView is the logical successor to the DataGrid and it uses control state properly, as do the new versions of the TextBox and DropDownList controls. following figure shows a list of the controls that currently make use of control state and what properties they store there for your reference.



The next thing I wanted to point out are the serialization improvements in v2.0. View state (and control state) serialization now uses a new mechanism implemented in ObjectStateFormatter instead of using LosFormatter. the new serializer serializes the same object graph into roughly half the size, and spends about half as much time in the serialization and deserialization process.

No more text: LosFormatter wrote to a TextWriter; ObjectStateFormatter writes to a BinaryWriter. This by itself doesn’t do much, other than it enables a some other improvements.

Token-based approach: LosFormatter wrote out strings to represent data types and embedded the data within <, > brackets. None of that anymore. ObjectStateFormatter capitalizes on the underlying binary model, and writes out a byte representing the following data, and then the data.

No more strings: The old formatter converted everything to strings (numbers, booleans etc.) to write into the TextWriter. The new one writes out bytes. This saves the cost of converting to and from a string.

More compact storage: Integers are stored as 7-bit encoded numbers. So most of them (values 0 – 255) just take a single byte instead of 4. In the case of booleans, there are simply two boolean-type tokens: a true one and a false one, so there is no additional cost to storing boolean data. DateTime is also special cased. Just the TickCount is saved, which by the way isn’t lossy as the string version is.

Indexing of strings: Lets say you had a DataGrid with a 100 cells. You’d have the word “Text” in view state a 100 times! This came from the Text property of TableCell. The StateBag type (that is used for ViewState) now saves property names using IndexedString. The ObjectStateFormatter special cases this type (like Pair and Triplet) to build a running table of strings. Each time a string is reused, it simply saves out a token referring to an IndexedString, and the index within this running table.

If we place a DataGrid on a form and bind it to the authors table in the pubs database, the size of the view state string in 1.x is 12,648 characters. If we do the same in 2.0, the size of view state is reduced to 6,728 characters, a reduction of nearly half. Following Figure shows the contrast in space required by view state in ASP.NET 1.x, ASP.NET 2.0, and the number of characters actually rendered to the page for a variety of input sizes.

View State Size Comparison

Without doing anything special, you can look forward to an immediate reduction in the size of your view state with the release of ASP.NET 2.0. This does not mean that you should stop thinking about whether your controls need view state to function properly or not, since it can still contribute significantly to the size of the response, as evidenced in Figure. 



Nikhil Kothari’s Weblog

UML : A Hands-On Introduction for Developers

June 14, 2007

I came across very good article for UML. This tutorial provides a quick introduction to the Unified Modeling Language.
UML : A Hands-On Introduction for Developers

CmsHttpContext Vs CmsApplicationContext

June 6, 2007

when I surfing on net I found very good article on MCMS API. I found its very useful.

Compared On CmsHttpContext CmsApplicationContext
Instance Only one instance can be created using Current property. When we call CmsHttpContext.Current, the request is send to the server and it will check the HttpContext for an existing CmsHttpContext. If it finds one, then it will returns that. Otherwise it will create a new instance of it with the current identity, save that in the HttpContext and returns the new one. Any number of instances can be created with the constructor. All the instances will be created with an authentication and mode.
Authentication It will take the correct authentication from the current HttpContext. The identity will be created accordingly (Windows Identity or Passport Identity or Forms Identity) and the correct token will be taken for the creation of a new context. There are four kind of Authentication available with four different type of overloads. The appropriate one can be used. For more info on this, check the PAPI help.
Where it can be used This one can be only used in application’s which comes under HttpContext (web applications and web services). This can be used in windows applications, web applications, console applications, web services, etc.
Mode An instance is created by the server with the mode, which depends on the request we send. It can’t be changed. Must switch the request to change the mode (it will create an instance with that mode). An instance can be created with any mode which is required. It can’t be changed, a new instance must be created with a different mode.
Duration Because this is used in web based, duration of the instance is small. It is possible to have long running sessions (duration of time from when an object is modified to when CommitAll() is called) using this. But it is not a good practice to have long sessions. Because long running sessions can block accessing a site.
Dispose() It is not necessary to dispose the instance always, it will automatically handled by the server – CmsEndRequestModule will call this, if there is a valid instance exist in HttpContext after the response is send to client. After the use of CmsApplicationContext instance it must be disposed. Otherwise it may give problems. For more
information check Creating scalable applications using the CmsApplicationContext.
RollBackAll() After calling RollBackAll(), the instance is invalid, but after the call to this method, if we don’t use the instance, no need to call Dispose(), server will handle that. If we use after calling this, then its a must to call Dispose() and get a new instance. After calling RollBackAll(), the instance is invalid and it must be disposed and a new instance must be created for future use.

There are few properties and a method which are only available in CmsHttpContext(driven from CmsAspContext). They are not available in CmsApplicaitonContext. They are Channel, ChannelItem, CmsQueryString, IsUsingTemplate, Posting, UserCacheKey, ChannelItemIsVisible and ResolveUrl (). For more information, check the PAPI documentation.

Reference Taken From :…

as such you will find lot of good articles in chester’s blog.