Time Vaidation via Regular Expression

July 5, 2007

The function takes an input string. The format of the regular expression needs some explaining. Let’s talk about what is allowed. Hours must be present and can be one or two digits. That is \d{1,2} at the start. After that must be a colon. Then the minutes (2 digits) must be present. After that, everything starts to become optional. However, if seconds are present, then there must be a colon and two digits. So the colon and \d{2} is surrounded by parentheses and then followed by a question mark. The question mark says that the whole grouping in parentheses must appear exactly zero or one time. Then we do another grouping that must appear zero or one time. Inside this grouping is a space followed by some characters. The brackets are an indicator that “one of the letters” is correct. So after the space must be an upper or lower case “a” or “p”. After that, an upper or lower case “m” can appear (the question mark after the bracket indicates that the “m” must appear zero or one time).

So, that whole regular expression is used to validate the incoming string. Assuming the string is valid, then we can look to see if the individual pieces are in the right ranges. We split the value into an array based on the colon. So, if the incoming string is “12:25” then we’ll have two values in our array: “12” and “25”. Note that if the incoming string is “12:25 PM”, we’ll still have two values: “12” and “25 PM”.

The first piece must be between 0 and 23. If there is an “a” or “p” in the value, then we set hasMeridian to true and the first piece must be between 1 and 12. The second piece must be between 0 and 59. The third piece, if present, must be between 0 and 59.

Note that we’re taking advantage of the way parseFloat works. If the string is “25 PM”, parseFloat will see the numbers at the start and then the space and stop evaluating – it will return a value of 25. So we don’t have to worry any more about the meridian part being in the value – it will not affect our evaluating of the range of numbers.

function isValidTime(value)
{
var hasMeridian = false;
var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/;

if (!re.test(value)) { return false; }

//check for time is in meridian or its 24hour?
if
(value.toLowerCase().indexOf(“p”) != -1) { hasMeridian = true; }
if (value.toLowerCase().indexOf(“a”) != -1) { hasMeridian = true; }

var values = value.split(“:”);

//Hours must be present and can be one or two digit.
//if time is not a meridian then value should less then 24 hour
//and greater then 0

if
( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; }

//if time is in meridian then value should less then 12 hour and
//greater then 1 hour
if
(hasMeridian)
 {
   if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) 
   { return false; }
 }

//Minutes must be present and can less then 60.
if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; }

//if Second part is present then it should be less then 60.
if (values.length > 2)
{
  if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) 
  { return false; }
}

 return true;
}

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

if (!isValidTime(myTimeString)) { alert(“The time is not in the correct format.”); }

Reference:
Breaking Par Consulting Inc.

happy programming!!!


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}$/
}
else
{ // 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.”); }

Reference:
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}

Reference:
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.

^[A-Za-z]\w{6,}[A-Za-z]$

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.

^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$

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 –   @#$%^&+=

^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

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

Reference:
Breaking Par Consulting
Anil John’s Blog


Making web pages printable using CSS

May 22, 2007

One of the classic problems with how web pages are designed, is that they are horrible to print. Horrible in the sense that page elements (text, images etc) don’t line up and unwanted images and navigation links get printed.

I am as guilty as anyone of creating pages like that, but I am aiming to fix it for your websites and mine. While most other web designers will create separate ‘printable’ pages (big waist of time), we will only be making some simple additions to our pages to make them ‘print friendly’.

Basic ideas:

  • People will print your pages typically to be able to read the content, not to see pictures. You need to hide all images from the printer and this is done in the print style sheet. I will explain what the print style sheet is in a moment.
  • Navigational elements are not needed in the printed document as well, so all navigational element should be removed from the printed page.
  • Let’s say you designed your pages with a black background with white text. You don’t want peoples printers printing all that black, they won’t be too happy with the price of ink these days! To solve this problem, in our print style sheet we will set the page color to ‘white’ and the text color to ‘black’.

The ‘print style sheet’:

I’ve mentioned the ‘print style sheet’ a few times with no explanation; let’s take care of that now. CSS today allows you to link to more than one style sheet in your web page.

The simple reason you would want to do this is so that you could have the HTML page ‘change’ it’s appearance automatically when someone visits your page with a particular type of device. These types of devices can include a typical desktop computer, a PDA (Windows CE device, Palm Pilot etc) and a printer among other devices!

It works like this; when you link a style sheet to your HTML page there is an attribute that you can specify in the CSS link tag that tells the device reading your page if it should use the style sheet specified in the link.

So the wise men and women that came up with the CSS specification, came up with a few ideas for device types that could be specified in the CSS link. For the sake of this short article we are concerned with only two of them:

1: ‘print’
2. ‘screen’

Here’s a sample pair of CSS links that point to different style sheets, one for the printer to use and the other for a normal PC monitor to use:

<link href=”CSS/webdesignersHanbook_Print.css” mce_href=”CSS/webdesignersHanbook_Print.css” rel=”stylesheet” type=”text/css” media=”print”>

<link href=”CSS/webdesignersHanbook_1.css” mce_href=”CSS/webdesignersHanbook_1.css” rel=”stylesheet” type=”text/css” media=”screen”>

You can see that these CSS links are actually taken from the Handbook on Killersites.com. What you’re looking for in the link is this text:

media=”print”
and
media=”screen

The first (‘media=”print”‘) points to the style sheet that has been set up for printing while the other (media=”screen”) is set up for normal PC monitors. Nowadays most browsers know that if someone tries to print the page the style marked with: ‘media=”print”‘ should be used.

So now we know how to tell the browser which style sheet to use when printing the HTML page, so what is different in the print style sheet that makes this work?

There are all kinds on things you can do, but the easiest is just to wrap HTML and images you don’t want printed with <div> tags and give all those <div> tags an ID of a style that is set to:

‘display: none’

What?!

Ok, the best way to understand is to see it work. Use the template for the CSS article on Killersites.com and create a new style sheet called something like ‘print.css’. In that style sheet you ad this:.noPrint {
display: none;
}
Now in your HTML pages just wrap DIV’s around elements you don’t want printed:

<div class=’noPrint’>
<p>Text that I don’t want printed.</p>
</div>

(Don’t forget to include your CSS links in the <head> of your HTML page!)

Those elements inside the DIV’s with the class ‘noPrint’ won’t print.

Another thing you should do is make all you text black and your pages white:

body {
font-family:
Georgia, “Times New Roman”, Times, serif;
font-size: 14px;
color: #000000;
background-color: #FFFFFF;

}

If you used font tags or set your font color on other tags (with CSS) in your HTML page you will have to change those as well, for example:

H1 {
color: #000000;
}

The above CSS sets all the H1 tags text to black.

If you used font tags you’re going to have to manually remove them and use CSS to style your fonts! That can be time consuming, but once you fix a site with crappy font tags, you will never use them again!

One last tip – create a print button on your page with this code:

<a href=”#” mce_href=”#” onClick=” window.print(); return false”>Print this page</a>

It’s just a link tag with a little bit of Javascript:

onClick=” window.print(); return false”