Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications
Use LinkBuilder
to convert text to HTML

Various regexp patterns


A pattern for matching a time value in the format HH:MM:SS (e.g., 14:30:00) :

/\d\d:\d\d:\d\d/;

Another time pattern:

/^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/ HH:MM or HH:MM:SS or HH:MM:SS.mmm

The pattern for matching a date in the format DD/MM/YYYY might be expressed as:

/\d{2}/\d{2}/\d{4}/;

Another date pattern in the mm/dd/yyyy format:
In this case, days and months can be expressed as one or two digits. A separator can be a dash (-) ,a slash ( / ) or a dot ( . )

/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
(| Matches the expression to the left or the right of the |_character.)


The pattern for matching a 5-digit zip code might be expressed as:

/\d{5}/;

Canadian postal code pattern

/^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/ Z5Z-5Z5 orZ5Z5Z5


IP Address(no check for valid values (0-255))

/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
999.999.999.999


The pattern for matching a U.S. Social Security Number might be expressed as:

/\d{3}\-\d{2}\-\d{4}/;

Another pattern for a Social Security Number with optional dashes.

/^\d{3}\-?\d{2}\-?\d{4}$/ 999-99-9999 or999999999

Canadian Social Insurance Number
/^\d{9}$/ 999999999

A money pattern, 2 decimals
/^\d+\.\d\d$/;

A money pattern , 2 decimals optional

/^\d+(\.\d{2})?$/;
Dollar Amount

/^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/ 100, 100.00, $100 or $100.00

Currencies

Amounts of money (in currencies with 100 minor units per major unit) should always be written either as an integer or with exactly two decimal places. The representation of the decimal point varies, and thousands separators may be allowed. Amounts smaller than 1.00 must start with a zero.

The basic RegExp is of the form /^\d+(\.\d\d)?$/

Another currency pattern:
/^-?\$?\d{1,3}(,\d{3})*(\.\d{1,2})?$/;

Valid Number
A valid number value should contain only an optional minus sign, followed by digits, followed by an optional dot (.) to signal decimals, and if it's present, additional digits. A regular expression to do that would look like this:

/(^-*\d+$)|(^-*\d+\.\d+$)/

Additional Resources:

Informit: JavaScript Programming Techniques