Wednesday, March 26, 2008

Validation with Regular Expression

Some useful Validation with Regular Expression here

  • Not empty = '/.+/'
  • Numbers [0-9] = '/^[-+]?\\b[0-9]*\\.?[0-9]+\\b$/'
  • A valid email address = '/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.
  • A valid year (1000-2999) = '/^[12][0-9]{3}$/'
  • Credit Card : 'amex' => '/^3[4|7]\\d{13}$/'
    'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/'
    'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/'
    'disc' => '/^(?:6011|650\\d)\\d{12}$/'
    'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/'
    'enroute' => '/^2(?:014|149)\\d{11}$/'
    'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/'
    'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/'
    'mc' => '/^5[1-5]\\d{14}$/'
    'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/'
    'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,
    'visa' => '/^4\\d{12}(\\d{3})?$/'
    'voyager' => '/^8699[0-9]{11}$/'
    'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])
  • url = '/^(?:(?:https?|ftps?|file|news|gopher):\\/\\/)?(?:(?:(?:25[0-5]|2[0-4]\d|(?:(?:1\d)?
i collected some source ... try..

how to write a Regular Expression

What Regular Expression?
A regular expression is a pattern that can match various text strings, used for validations.

Where and when to use Regular Expression?
It can be used in the programming languages which supports or has regular expression class as in built or it supports third party regular expression libraries.

Regular expressions can be used to valid different type of data without increase the code with if and case conditions. A number of if conditions can be omitted with single line of regular expression checking.

Benefits of Regular Expression:
The following are benefits (not all included) of use of Regular Expression.
a) # line of code can be reduced.
b) Speed Coding.
c) Easy maintenance (you don’t need to change if validation criteria changes, just check the regular expression string).
d) Easy to understand (you don’t need to understand the programmer logic on large if statements and case statements).

Elements of Regular Expression:
Here are the basic elements of regular expression characters/literals, which can be used to build big regular expressions:

^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
\ ---->Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.
\w ----> matches any word character, equivalent to [a-zA-Z0-9]
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9].
\s ----> matches any white space character, equivalent to [\f\n\r\v]
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v]
\d ----> matches any decimal digits, equivalent to [0-9]
\D----> matches any non-digit characters, equivalent to [^0-9]

\a ----> Matches a bell (alarm) \u0007.
\b ----> Matches a backspace \u0008 if in a [] character class; otherwise, see the note following this table.
\t ---->Matches a tab \u0009.
\r ---->Matches a carriage return \u000D.
\v ---->Matches a vertical tab \u000B.
\f ---->Matches a form feed \u000C.
\n ---->Matches a new line \u000A.
\e ---->Matches an escape \u001B

$number ----> Substitutes the last substring matched by group number number (decimal).
${name} ----> Substitutes the last substring matched by a (? ) group.
$$ ----> Substitutes a single "$" literal.
$& ----> Substitutes a copy of the entire match itself.
$` ----> Substitutes all the text of the input string before the match.
$' ----> Substitutes all the text of the input string after the match.
$+ ----> Substitutes the last group captured.
$_ ----> Substitutes the entire input string.

(?(expression)yes|no) ----> Matches yes part if expression matches and no part will be ommited.

Simple Example:
Let us start with small example, taking integer values:
When we are talking about integer, it always has fixed series, i.e. 0 to 9 and we will use the same to write this regular expression in steps.

a) Regular expression starts with “^”
b) As we are using set of characters to be validated, we can use [].
c) So the expression will become “^[1234567890]”
d) As the series is continues we can go for “-“ which gives us to reduce the length of the expression. It becomes “^[0-9]”
e) This will work only for one digit and to make it to work for n number of digits, we can use “*”, now expression becomes “^[0-9]*”
f) As with the starting ending of the expression should be done with “$”, so the final expression becomes “^[0-9]*$”

Note: Double quotes are not part of expression; I used it just to differentiate between the sentences.

Is this the way you need to write:
This is one of the way you can write regular expression and depending on the requirements and personal expertise, regular expression could be compressed much shorter, for example above regular expression could be reduced as.

a) Regular expression starts with “^”
b) As we are checking for the digits, there is a special character to check for digits “\d”
c) And digits can follow digits , we use “*”
d) As expression ends with “$”, the final regular expression will become

Digits can be validated with different ways of regular expressions:

1) ^[1234567890]*$
2) ^[0-9]*$
3) ^\d*$

Which one to choose?
Every one of above expressions will work in the same way, choose the way you are comfort, it is always recommended to have a smaller and self expressive and understandable, as these will effect when you write big regular expression.

Example on exclude options:
There are many situation which demands us to exclude only certain portion or certain characters,
Eg: a) Take all alpha numeric and special symbols except “&”
b) Take all digits except “7”
then we cannot prepare a big list which includes all instead we use the symbol of all and exclude the characters / symbols which need to be validated.
Eg: “^\w[^&]*$” is the solution to take all alpha numeric and special symbols except “&”.

Other Examples:
a) There should not be “1” as first digit,?
^[^1]\d*$ ? this will exclude 1 as first digit.

b) There should not be “1” at any place?
^\d[^1]*$ ? this will exclude the 1 at any place in the sequence.

Note: Here ^ operator is used not only to start the string but also used to negate the values.

Testing of Regular expression:
There are several ways of testing this
a) You can write a windows based program.
b) You can write a web based application.
c) You can even write a service based application.

Windows base sample code:
Here are steps which will be used for regular expression checking in dotNet:

a) Use System.Text.RegularExpression.Regex to include the Regex class.
b) Create an Regex object as follows:
Regex regDollar= new System.Text.RegularExpressions.Regex("^[0-9]*$ ");
c) Call the IsMatch(string object) of the Regex call, which will return true or flase.
d) Depending on the return state you can decide whether passed string is valid for regular expression or not.]

Here is the snap shot code as function:

Public boolean IsValid(string regexpObj, string passedString)
//This method is direct method without any exceptional throwing..
Regex regDollar= new System.Text.RegularExpressions.Regex(regexpObj);
return regDollar.IsMatch(passedString);

With minor changes to the above function it can be used in windows or webbased or even as a service.
source :

Thursday, March 13, 2008

Downloading Files From MySQL Database

Downloading Files From MySQL Database

When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.

The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3. To see a working example click here. I saved several images in my database, you can try downloading them.

more info:

Uploading Files To MySQL Database

More info :

Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).

For the first step, let's make the table for the upload files. The table will consist of.

  1. id : Unique id for each file
  2. name : File name
  3. type : File content type
  4. size : File size
  5. content : The file itself

For column content we'll use BLOB data type. BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :

  • BLOB

Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).


More info :

Monday, March 10, 2008

A Step-by-Step Guide To Using MySQL with ASP.NET

Many people have asked me for this tutorial, so here goes.

For those of you who don't know, MySQL is an open-source DataBase server. Being that it's open-source, it's also free. That's about as low-cost as you can get. Of course, you may ask 'Why use MySQL'? Did you read the previous sentences?? It's free, as well as being a fairly robust database server!

To be able to use MySQL, there are a couple of downloads that must be done:

  1. MySQL Itself
  2. MySQL ODBC Driver
The Database Server (MySQL), itself can be downloaded here:

The Driver (for Windows) can be downloaded here:

The biggest hurdle in using MySQL, is the setup - much like many other users of MSDE have found out. Without a user interface, it's quite cumbersome, requiring a command prompt to do all the work. Here's the best page I've found so far to take you, step-by-step through this process:

Now, once this is all set up - guess what - you have no data. If you want, the above installation page will also help you get started creating databases, tables and fields for your sample data. But, if you want a much quicker way to populate your database server, so you can get started, AugustWind Software has user interface for MySQL called Data Management Toolkit. Check it out here

Now - the part you actually came here for - - the easy part!

On other parts of this site, you've seen many samples, using MS Access and SQL Server. As you might have noticed, there are only three major differences in using these.

  1. Namespaces used
  2. Connection String
  3. Prefix to data classes (like: OleDbDataAdapter vs. SQLDataAdapter, specific to the Imported Namespaces
For MySQL, the driver which you downloaded (above), is an ODBC Driver, therefore, numbers 1 and two in the above list use 'ODBC':
<%@ Import Namespace="System.Data.ODBC" %>
And, you use classes like ODBCDataAdapter, ODBCDataReader, ODBCCommand, etc.

To finish out the three items in the above list, here, we show you the Connection String needed:

"Driver={MySQL ODBC 3.51 Driver};uid=YourUID;password=YourPWD;Server=YourServerIP;Option=16834;Database=YourDB;"
or, you can use:
Just change these few things, in your code, and you're off and running, using MySQL in your own ASP.Net documents!

Now, do you believe me, when I say that using MySQL in your ASP.Net documents is the easy part? In fact, if you have a hosted web site, chances are, most of the setup can be done by someone else and all you will need to do is the pages themselves!

Now, you can't put off using MySQL, for lack of knowledge!

To see a full code sample, check out this page:
To see a code sample with ASP.Net 2.0, check out:

Thursday, March 6, 2008

In and out of PHP before they even knew what hit 'em

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:

Hey Turkeys! Behind ya!

I just drop by with present for warming of house, instead find you grappling with

Hopefully that last one didn't confuse you as much it confused me, the example is a bit extreme. However look over it a few times and you will understand exactly what is going on.

They true did false, they were the trueiest bunch of falses that ever trued

If all you are trying to test for is a boolean (true/false) of a variable or function then instead of laying down a bunch of code like this:

if ($blackbeard == true) echo 'Arr, this chair be high, says I.';
elseif ($seacaptain == false) echo 'Yar, I'm not attractive.';

You can omit == and != with:

if ($blackbeard) echo 'Arr, this chair be high, says I.';
elseif (!$seacaptain) echo 'Yar, I'm not attractive.';

This same format can apply to functions and multiple conditions. For example:

if ($benedict_arnold != true && strpos($photo,'map') == true)
echo 'You idiot, you can't read!';

if (high_chair($blackbeard) == false)
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

The following is the same exact statement (except with less code):

if (!$benedict_arnold && strpos($photo,'map'))
echo 'You idiot, you can't read!';

if (!high_chair($blackbeard))
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

One control structure to rule them all, One constant to find them, One set of conditional brackets to bring them all and in the darkness bind them

Not anymore! If you have a single expression following a control structure, you do not need to waste your time with brackets { }.

if ($gollum == 'halfling') {
$height --;

Is the same as:

if ($gollum == 'halfling') $height --;

This can be applied to any control structure statement. For example:

if ($gollum == 'halfling') $height --;
else $height ++;

if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';

foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';

The fewer brackets you have cluttering up your code, the easier it may be to read.

Single Quotes versus Double Quotes

Any time you put something in "double" quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.

$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }

Those same three lines of code could be executed much faster if 'single' quotes were used in place of "double" quotes.

$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }

Now that may not seem like much, but having PHP check for variables where it doesn't need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within 'single' quotes.

echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:

echo $mytext . 'Lisa needs braces.';

As opposed to this bit of molasses-like code:

echo "$mytext Lisa needs braces.";

It All Adds Up

$variable = $variable + 1;

Is the same as:

$variable ++;

This method also works for subtraction:

$variable --;

You can also apply a similar method for concocting strings. So instead of:

$mytext = 'Done and Done.';
$mytext = "$mytext And I mean Done!"; // $mytext = 'Done and Done And I mean Done!';

Use this shorthand method of adding another string of text onto the end of the first string:

$mytext = 'Done and Done.';
$mytext .= ' And I mean Done!'; // $mytext = 'Done and Done And I mean Done!';