Wednesday, September 12, 2007
Visual Confirmation Code
System.Data
System.Drawing
System.IO
System.Text
System.Security.Cryptography
########################
###The Code Goes here
########################
Dim strVisualString As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not IsPostBack = True Then
GenerateVisualConfirmationCode()
End If
End Sub
Sub GenerateVisualConfirmationCode()
Dim str As String = Server.MapPath("../images/VisualConfirmation/test1.jpg")
Dim str2 As String = Server.MapPath("../images/VisualConfirmation/test3.jpg")
If System.IO.File.Exists(str2) Then
System.IO.File.Delete(str2)
End If
Dim b As New System.Drawing.Bitmap(str)
Dim f As New Font("Arial", 30)
Dim graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(b)
Dim width As Integer = CInt(graphics.MeasureString("ABCDEFGH", f).Width)
Dim height As Integer = CInt(graphics.MeasureString("ABCDEFGH", f).Height)
b = New Bitmap(b, New Size(200, 50))
graphics = System.Drawing.Graphics.FromImage(b)
'graphics.Clear(Color.DarkBlue)
graphics.Clear(Color.White)
strVisualString = RandomString(6)
graphics.DrawString(strVisualString, f, New SolidBrush(Color.Black), 0, 0)
graphics.Flush()
b.Save(str2, System.Drawing.Imaging.ImageFormat.Jpeg)
End Sub
Function RandomString(ByVal iLength As Integer) As String
Dim iZero, iNine, iA, iZ, iCount, iRandNum As Integer
Dim sRandomString As String
Dim rRandom As New Random(System.DateTime.Now.Millisecond)
iZero = Asc("0")
iNine = Asc("9")
iA = Asc("A")
iZ = Asc("Z")
sRandomString = ""
While (iCount < iLength)
iRandNum = rRandom.Next(iZero, iZ)
If ((iRandNum >= iZero) And (iRandNum <= iNine) Or (iRandNum >= iA) And (iRandNum <= iZ)) Then
sRandomString = sRandomString + Chr(iRandNum)
iCount = iCount + 1
End If
End While
RandomString = sRandomString
End Function
Thursday, June 21, 2007
Non ASCII Characters with MySQL
Storing Non ASCII Characters in Database
MySQL can store non ASCII characters in database in a number of encodings, MySQL call them character sets:
+----------+-----------------------------+
Charset Description
+----------+-----------------------------+
big5 Big5 Traditional Chinese
dec8 DEC West European
cp850 DOS West European
hp8 HP West European
koi8r KOI8-R Relcom Russian
latin1 ISO 8859-1 West European
latin2 ISO 8859-2 Central European
swe7 7bit Swedish
ascii US ASCII
ujis EUC-JP Japanese
sjis Shift-JIS Japanese
cp1251 Windows Cyrillic
hebrew ISO 8859-8 Hebrew
tis620 TIS620 Thai
euckr EUC-KR Korean
koi8u KOI8-U Ukrainian
gb2312 GB2312 Simplified Chinese
greek ISO 8859-7 Greek
cp1250 Windows Central European
gbk GBK Simplified Chinese
latin5 ISO 8859-9 Turkish
armscii8 ARMSCII-8 Armenian
utf8 UTF-8 Unicode
ucs2 UCS-2 Unicode
cp866 DOS Russian
keybcs2 DOS Kamenicky Czech-Slovak
macce Mac Central European
macroman Mac West European
cp852 DOS Central European
latin7 ISO 8859-13 Baltic
cp1256 Windows Arabic
cp1257 Windows Baltic
binary Binary pseudo charset
geostd8 GEOSTD8 Georgian
+----------+-----------------------------+
To store non ASCII characters in a database column, you need to define that column with
a specific character set. You can specify a character set at 3 levels: database, table, and column.
For example:
CREATE DATABASE db_name CHARACTER SET utf8
CREATE TABLE tbl_name (...) CHARACTER SET utf8
CREATE TABLE tbl_name (col_name CHAR(80) CHARACTER SET utf8, ...)
- If a character set is specified at the database level, it is applied to all CHAR, VARCHAR,
and TEXT columns of all tables in this database. - If a character set is specified at the table level, it is applied to all CHAR, VARCHAR,
and TEXT columns in this table. - If a character set is specified at the column level, it is applied to this column only.
- The column length specified in the table creation statement is counted at the character level,
not at the encoding byte level. - If "utf8" is used on a CHAR(n) column, this column will require 3*n bytes of storage.
Transmitting Non ASCII Characters to the Server
Handling non ASCII characters with MySQL not only requires us setting up the table columns
with the correct encoding (character set), but also requires us setting up the correct encoding
for transferring characters to and from the database.
MySQL offers the following variables to control the encodings used to transfer characters between
the client (PHP script) and the server (MySQL database):
- character_set_server - Character set used for all databases on the server.
- character_set_database - Character set used for the default databases on the server.
- character_set_client - Character set used by the client for all SQL statements.
- character_set_connection - Character set that all SQL statements should be converted to
by the server before executing them. - character_set_results - Character set that all returning result should be converted to
by the server before sending it back to the client.
In most cases, you should make the client (PHP script) to use the same encoding (character set)
as the server (MySQL server), so that there is no need to convert when transferring characters between them.
Some times, you may need to use different encodings. For example, you want to use UTF-8 for your PHP scripts,
while using GB2312 for your MySQL tables.
You can use two special SET commands to change those variables:
1. "SET NAMES 'x'" is equivalent to these three statements:
SET character_set_client = x;
SET character_set_results = x;
SET character_set_connection = x;
2. "SET CHARACTER SET x" is equivalent to these three statements:
SET character_set_client = x;
SET character_set_results = x;
SET collation_connection = @@collation_database;
You can always use the SHOW VARIABLES LIKE 'variable_name' to view the current value of the given variable.
MySqlUnicode.php - UTF-8 Sample Script
My is my sample script to show you how to send UTF-8 strings to a MySQL server and store them
in UTF-8 encoding, MySqlUnicode.php:
<?php # MySqlUnicode.php
# Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
#
$con = mysql_connect('localhost');
print "\nDefault settings...\n";
$rs = mysql_query("SHOW VARIABLES LIKE 'character_set_%'");
while ($row = mysql_fetch_array($rs)) {
print " ".$row[0].' '.$row[1]."\n";
}
print "\nUpdated settings...\n";
$rs = mysql_query("SET NAMES 'utf8'");
$rs = mysql_query("SHOW VARIABLES LIKE 'character_set_%'");
while ($row = mysql_fetch_array($rs)) {
print " ".$row[0].' '.$row[1]."\n";
}
print "\nCreating a table in UTF-8...\n";
$rs = mysql_query('DROP DATABASE MyBase');
$rs = mysql_query('CREATE DATABASE MyBase CHARACTER SET utf8');
$rs = mysql_query('USE MyBase');
$rs = mysql_query('CREATE TABLE MyTable (ID INTEGER,'
.' Message VARCHAR(80))');
print "\nInserting some rows to the table...\n";
$str = "Hello!";
$rs = mysql_query("INSERT INTO MyTable VALUES ( 1, '$str')");
$str = "\xC2\xA1Hola!";
$rs = mysql_query("INSERT INTO MyTable VALUES ( 2, '$str')");
$str = "\xE4\xBD\xA0\xE5\xA5\xBD!";
$rs = mysql_query("INSERT INTO MyTable VALUES ( 3, '$str')");
print "\nQuery some rows from the table...\n";
$rs = mysql_query('SELECT * FROM MyTable WHERE ID < 10');
print " ".mysql_field_name($rs,0)." "
.mysql_field_name($rs,1)."\n";
while ($row = mysql_fetch_array($rs)) {
print " ".$row[0].' '.$row[1]."=(\x".bin2hex($row[1]).")\n";
}
mysql_free_result($rs);
mysql_close($con);
?>
If you run it, you will get:
Default settings...
character_set_client latin1
character_set_connection latin1
character_set_database latin1
character_set_results latin1
character_set_server latin1
character_set_system utf8
character_sets_dir C:\local\MySQL\share\charsets/
Updated settings...
character_set_client utf8
character_set_connection utf8
character_set_database latin1
character_set_results utf8
character_set_server latin1
character_set_system utf8
character_sets_dir C:\local\MySQL\share\charsets/
Creating a table in UTF-8...
Inserting some rows to the table...
Query some rows from the table...
ID Message
1 Hello!=(\x48656c6c6f21)
2 -íHola!=(\xc2a1486f6c6121)
3 S+ásÑ+!=(\xe4bda0e5a5bd21)
MySQL works as we expected, no conversion on the SQL statements, storing strings in UTF-8, and no conversion
on query result.
Conclusion
- MySQL provides a good support on non ASCII characters. If offers a number of encodings (character sets).
- MySQL allows to specify encodings at database, table or column level.
- MySQL allows to control encoding conversions on receiving SQL statements and returning query results.
- My recommendation is to use UTF-8 to all text information, turn off MySQL encoding conversion on receiving
SQL statements and returning query results, and let your PHP script to handle UTF-8 strings.
Tuesday, June 19, 2007
Introduction to Application Object in ASP.NET
Before we understand the events, we need to know the steps that a Web request goes through during its life cycle. The request begins with the client browser and continues till the request is completely processed and the response (if any) is sent back to the client.
Order of execution
This lifecycle is called the ASP.NET pipeline. Here is how the pipeline looks. It is a step-by-step process through which various parts of the request are processed in a structured manner.
The order is as follows:
Events
Here are the types of events.
1. Events which always occur for every request
a. Request related events
b. Response related events
2. Events which occur only under certain conditions
Events which occur for each request
a) Request related events:
These events occur when a new request is received. These are listed in the order of occurrence.
Event: Application_OnBeginRequest
Comment: Raised for each request. Even for Web service requests
Event: Application_OnAuthenticateRequest
Comment: Raised when authentication is about to begin
Practical Usage: Use this to override the default authentication mechanism and write completely custom authentication code here.

When do you use this? When you require an authentication mechanism that does not fit into the default authentication methodologies given with .NET.
Further, you can use this during the development phase to quickly override the base authentication mechanism.
During production phase, simply remove this event code.
Event:Application_OnAuthorizeRequest
Comment:Raised when authorisation is about to begin. This decides what privileges to offer the current requestor.
Practical Usage: Again used to override the default authorisation and replace it with custom authorisation.
Event: Application_OnResolveRequestCache
Comment: This one is used in Page Caching. Page Caching stores page output in a cache and later serves similar requests from the cache. This increases performance dramatically.
This event is used by ASP.NET to decide whether to rerun the page code or deliver the page from the cache.
Practical Usage: Writing code for this event allows you to customise how page caching works. Further it also allows you to write code that can execute for each request, irrespective of whether the page was delivered from page cache or from the ASPX page.
For example, you can use this for generating an audit trail or performance log or for incrementing online page view counters.
Event: Application_OnAcquireRequestState
Comment: Event fires when the Session state is about to be populated for the request.
Practical Usage: Your code can customise the content of the Session stateThis is done when you want a pre-created custom item to be inserted in the Session state. This can then be handled by the page or Web service.
This will centralise the code that we often write in the page level events.
It is important to cross check with your existing code, to judge which piece of code can be better handled in this event.
Event: Application_OnPreRequestHandlerExecute
Comment:Before the page handler (or Web service handler) is called for the incoming request.
Practical Usage: Useful if you want to perform some operations before the default page handler takes over.
b) Response related events:
Event: Application_OnUpdateRequestCache
Comment:This is raised when ASP.NET decides to update the Page Output cache by actually executing a page.
Practical Usage: Write custom code here to monitor cache refresh rate (to judge the effectiveness of page caching in your application).
Event: Application_OnReleaseRequestState
Comment:Occurs when the Session data is released.
Practical Usage: Custom objects created on OnRequestState can be now handled.
Event: Application_OnPostRequestHandlerExecute
Comment: Raised after the default handler finishes execution.
Practical Usage: Used to create custom HTTP header and body.
Event: Application_OnEndRequest
Comment: Corresponding to BeginRequest.

Practical Usage: Last event to fire. Cleanup tasks are best done here.
If you want to add something to ALL pages within an application do it here.
Event: PreSendRequestHeaders and PreSendRequestContent
Comment: These events fire after the entire data is ready to be sent as the client response.
Practical Usage: Pre-event is fired when HTTP headers are sent. If you want to change any content, you must update the operation before this event fires. Otherwise, wrong size information would be sent in the header.
The content event fires after the entire body text is sent to the client.
Of all these events the EndRequest event is guaranteed to occur. This event is the place which you should use to perform tasks which require to be done after request completion – including cleanup, in this event code.
Conditional events
Event: Application_OnStart
Comment: This one is familiar to all ASP developers. This occurs only once per application when it starts. Practical Usage: One-time tasks can be done here. These could be data connections, adding data that is likely to be used frequently to cache objects, setting values for variables and so on.
Event: Application_OnEnd
Comment: Occurs when application ends.
Practical Usage: Generally used to cleanup things that were set up during the application execution period.
Event: Session_OnStart
Comment: Fires for each user when the session begins.
Practical Usage: Setting user specific values, caching items based upon user context.
Event: Session_OnEnd
Comment: Opposite of the previous event.
Practical Usage: User Specific Cleanup, audit trail, usage statistics, logging how the state terminated and so on.
Event: Application_Error
Comment: When unhandled error occurs.
Practical Usage: Good for logging errors, logging additional environmental information, notifying administrators depending upon type of error, taking global actions to manage impact of errors.
Event: Application_OnDisposed
Comment: Occurs when CRL removes the application from memory.
Practical Usage: Additional cleanup procedures.
CompleteRequest method
This method is used to bypass normal processing of the HTTP request. If you handle some event with custom code and then you do not want the control to pass to further default event handlers in the request processing chain, call this method. This method, when called, ignores all further handlers and then raises EndRequest event.
HTTP modules
Handlers for various HTTP functions are configured using HTTPModules. These modules are defined in ‘machine.config’ and can be overridden in ‘web.config’.
Various modules are utilised in serving a particular request. It is possible to write your own custom HTTP modules for implementing special functionality not available within .NET.
The HTTP handler is the class which manages the actual HTTP request. By default this is the page class in ‘system.web.ui.page’ namespace.
To create an HTTP module, you need to write a class which implements the IHTTPModule interface. To inform the runtime to use the custom module, you need to modify the ‘web.config’ file.
Handlers for various types of files are mapped in IIS application configuration settings.
The diagram below shows the ASP.NET file extensions and the relevant handlers.
Global.ASAX
All the custom code for overriding the Application events is written here. This file is optional. But if you need to customise the application event management logic, you need to create this and write code in it.
Thursday, June 14, 2007
MS SQL SERVER 2000 Questions (Database Design)
As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.
How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
It will be a good idea to read up a database designing fundamentals text book.
What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.
What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
See sp_addtype, sp_droptype in books online.
What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.
ASP Date() And Time() Functions
Returns the current date & time like this ....
6/5/2007 6:34:52 AM
--------------------------------------------------------------------------------
Returns the current date like this ....
6/5/2007
--------------------------------------------------------------------------------
Returns the current time like this ....
6:34:52 AM
--------------------------------------------------------------------------------
Returns the current year like this ....
2007
--------------------------------------------------------------------------------
Returns the current month like this ....
6
--------------------------------------------------------------------------------
Returns the current day like this ....
5
--------------------------------------------------------------------------------
Returns the current hour like this ....
6
--------------------------------------------------------------------------------
Returns the current minute like this ....
34
--------------------------------------------------------------------------------
Returns the current second like this ....
52
--------------------------------------------------------------------------------
Ok ..... You got the hang of that? We will now start jazzing things up a bit.
Returns the current date & time like this ....
6/5/2007 6:34:52 AM
--------------------------------------------------------------------------------
Returns the current date like this ....
Tuesday, June 05, 2007
--------------------------------------------------------------------------------
Returns the current date like this ....
6/5/2007
--------------------------------------------------------------------------------
Returns the current time like this ....
6:34:52 AM
--------------------------------------------------------------------------------
Returns the current time like this ....
06:34
--------------------------------------------------------------------------------
Returns the current month like this ....
June
--------------------------------------------------------------------------------
Returns the current month like this ....
Jun
--------------------------------------------------------------------------------
Returns the current day like this ....
3
--------------------------------------------------------------------------------
Returns the current day like this ....
Tuesday
--------------------------------------------------------------------------------
Returns the current day like this ....
Tue
--------------------------------------------------------------------------------
OK ... Let's take all this a little further
Returns what the date will be in 10 days time like this ....
6/15/2007 6:34:52 AM
--------------------------------------------------------------------------------
Returns what the date was 3 days ago like this ....
6/2/2007 6:34:52 AM
--------------------------------------------------------------------------------
Returns the number of days that have passed since the 24th of March 2002
1899
--------------------------------------------------------------------------------
Returns the date in typical UK format
5/6/2007
--------------------------------------------------------------------------------
Returns the date in typical USA format
6/5/2007
--------------------------------------------------------------------------------
Returns today's date like this ......
Tuesday, 5 June, 2007
ASP String Functions
String functions are a great way to manipulate and parse the data within your strings, below are some of the most commonly used ones. For our purposes, we will use this variable as an example:
strExample = "These are examples of string functions."
InStr
//Code
DIM strPosition
strPosition = InStr(1, strExample, "examples", 1)
Response.Write strPosition
//Code
In this example, our script returns the value: 11 . The InStr function is a powerful tool that searches text strings and returns the position of a given text substring. In this case, we search the strPosition string for the "example" and our script returns "11", which is the starting position of the word within the string.
Left
//Code
DIM strLeftText
strLeftText = Left(strExample, 18)
Response.Write strLeftText
//Code
In this example, our script returns the value: " These are examples ". The Left function takes a string and returns a specified number of characters starting from the left side.
Right
//Code
DIM strRightText
strRightText = Right(strExample, 10)
Response.Write strRightText
//Code
In this example, our script returns the value: " functions. ". The Right function takes a string and returns a specified number of characters starting from the end of the string.
Mid
//Code
DIM strMidText
strMidText = Mid(strExample, 11, 8)
Response.Write strMidText
//Code
In this example, our script returns the value: " examples ". The Right function takes a string and returns a specified number of characters starting from the end of the string.
Trim, LTrim, and RTrim
//Code
DIM strTrimText, strLTrimText, strRTrimText
strTrimText = Trim(strExample)
strLTrimText = LTrim(strExample)
strRTrimText = RTrim(strExample)
Response.Write strTrimText
Response.Write strLTrimText
Response.Write strRTrimText
//Code
In this example, all three atrTrimText, strLTrimText, and strRTrimText return our original example: "These are examples of string functions." LTrim is used to remove blank spaces at the beginning of a string. RTrim is used to remove blank spaces at the end of a string. Trim is used to remove spaces from both the beginning and the end of a string.
LCase and UCase
//Code
DIM strLCaseText, strUCaseText
strLCaseText = LCase(strExample)
strUCaseText = UCase(strExample)
Response.Write strLTrimText
Response.Write strRTrimText
//Code
In this example, strLCaseText returns the value: " these are examples of string functions. " and strUCaseText returns the value: " THESE ARE EXAMPLES OF STRING FUNCTIONS. ". As you can tell, the LCase function returns all lower case letters and the UCase function returns all upper case letters. These functions are especially useful for inserting and updating records in your database because they help keep your data consistent.
Len
//Code
DIM intLenText
intLenText = Len(strExample)
Response.Write intLenText
//Code
In this example, intLenExample returns the value: " 39 " . The Len function returns the number of characters in a given string.
String
//Code
DIM strMyExample
strMyExample = String(1, 97)
Response.Write strMyExample
//Code
In this example, strMyExample returns the value: " a " . The String function takes a character code (97) and returns its character (a). The (1) in this case controls how many time the "a" will be displayed.
Wednesday, June 13, 2007
Use of Regular Expression in Javascript
var fnameRegxp = /^([a-zA-Z]+)$/;
This statement checks that only upper or lowercase case letters, repeated one or more times, pass the validation test, which, unless you’re hoping to send your newsletter to C3PO, should be the case. Remember when I mentioned that regular expressions can still return true if there are incorrect characters present, provided that the correct pattern of characters is somewhere within the string? Putting the circumflex and dollar sign at the beginning and end of the regular expression ensures that this does not happen, and that the string is only valid if it contains just what you’re asking for.
var lnameRegxp = /^([a-zA-Z]+)$/;
var houseRegxp = /^([0-9A-Za-z]+)$/;
These then check that the surname entered is also any upper or lowercase character repeated one or more times, and that the house name consists of just numbers and letters. You could have shortened this to /^([\w]+)$/ using the shorthand escape code for "any word character," but that would allow underscores to be used, which rarely feature in property names.
var pcodeRegxp = /^([A-Za-z]{1,2})([0-9]{2,3})([A-Za-z]{2})$/;
var telnoRegxp = /^([0-9]{11})$/;
I’ve used local examples for the post code (the UK version of a zip code) and telephone regular expressions. UK postcodes are in a format consisting of one or two letters, followed by two or three numbers (depending on the county), and followed again by two letters. It should be easy to see how you could change this to match your own local form of postal or zip code and telephone number formats. The phone number check simply ensures that the correct number of numbers is present. Following these comes the most complex of regular expressions -- those that check for valid email addresses and URLs:
var emailRegxp = /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/;
var urlRegxp = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([\w]+)(.[\w]+)/;
Due to sub-domains, there may be any number of characters and dots preceding the @ sign. The first of these expressions says that any word character displayed one or more times can then be followed by a dot, then any number of word characters displayed zero or more times, followed by the @ symbol, followed by any word character displayed one or more times, followed by a dot and two or three word characters repeated at least once but no more than twice, so email addresses ending in .com or .co.uk will pass, whereas .co.uk.com would fail. Similarly, the URL may begin with either http://www. or https://www. or ftp://www. or just www. once followed by any word character one or more times, followed by a dot and any number of word characters at least once but no more than twice.
Finally, the date of birth check allows dates in the format dd/mm/yyyy or dd-mm-yyyy, both formats being equally as popular:
var dobRegxp = /^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-)([0-9]){4}$/;
We then need to actually test that each of the values submitted are in the correct format. I accomplished this by using a series of nested if statements and alerts. This method is useful for demonstration and testing purposes, although in reality, a for…next loop would probably be more efficient, and some kind of color highlighting scheme that would flag the erroneous input values a different color, say red, on the form itself would be more professional. The example if statements and alerts however, can be constructed as follows:
if (fnameRegxp.test(fname) != true)
alert("First name appears to be incorrect");
if (lnameRegxp.test(lname) != true)
alert("Last name appears to be incorrect");
if (houseRegxp.test(house) != true)
alert("Address 1 appears to be incorrect");
if (pcodeRegxp.test(pcode) != true)
alert("Address 2 appears to be incorrect");
if (telnoRegxp.test(telno) != true)
alert("Telephone number appears to be incorrect");
if (emailRegxp.test(email) != true)
alert("Email address appears to be incorrect");
if (email != verEmail)
alert("Email appears to be incorrect");
if (urlRegxp.test(url) != true)
alert("URL appears to be incorrect");
if (dobRegxp.test(dob) != true)
alert("Date of Birth appears to be incorrect");
Notice that instead of using a regular expression to check that the second email address entered (that should be the same as the first for verification purposes) is correct, we simply check that its value is exactly the same as the first email address entered.
Finally, if all of the data is in the correct format, we need this program to output a "Data Correct" alert and change the value of the action property of the form to the name of the cgi function that will process the data. Once again, against a professional backdrop, the true alert would probably be removed in favor of a fresh page thanking the visitor for their time, but this is useful for demonstration and
testing purposes:
else {
alert("Data Correct");
document.myForm.action.value = "process.cgi";
}
}
Another benefit to using regular expressions to validate user input is that any fields that are checked against a regular expression fail if the field is left blank, so you don’t have to write any separate omission checking functions.
Explaining regular expressions is almost as difficult as coding them. It will be far easier for you to see what I mean by writing and playing around with them yourself. Unfortunately, it is not possible to be 100 percent certain that all information entered is correct, but with regular expressions you can at least be sure that 99 percent of the data is correct.
Although this may seem like a cumbersome amount of code, without regular expressions, it would be ten times as long. Using client-side validation is not the securest way to validate your forms, but it may save processing time on your server by ensuring that only correct data is passed to it in the first place. Other than that, JavaScript is both quick and easy to implement and the regular expressions subset of the language is simpler than that of some of the more powerful Web programming languages, so for sites that don’t need maximum security, it is certainly worth considering.