Practicing with Regular Expressions
Comment about Regular Expressions from PHP5 Unleashed by John Coggeshall
"Regular expressions (regex) are one of the black arts of practical computer programming. Ask any programmer, and chances are that he or she will, at some point, have had serious problems with them (or, even worse, avoided them altogether.)"
Regular Expression
A way of describing a pattern in text - for example, "all the words that begin with the letter A" or "every 10-digit phone number" or even "Every sentence with two commas in it, and no capital letter Q".
From http://pronto.jrc.it/manual/glossary.html
To program form validation, you have to make use of "regular expressions" because you have to check user entry for the patterns you will allow in your database.
Patterns we will allow in our form:
- First Name: letters and one space only [a-zA-Z]
- Last Name: letters, hyphens, up to 5 spaces and apostrophes only
- Email address: letters, numbers, underscores, periods, and @.
Must contain the following: at least one letter, @, at least one letter, period, at least 2 letters.
- Phone: exactly 3 numbers, hyphen, exactly 3 numbers, hyphen, exactly 4 numbers.
Exercise 1: Create code to test for a letter
In this exercise, we will create a form that will test user entry with regular expressions.
- Open the file you created in the Forms exercise and save it as RegularExpression.htm.
- Rename the form ExpressionTest. Remove the first textbox.
- Rename the second textbox Word and use "Type a word or phrase" as the label.
- Change the function call in the form to TestA.
- Change the function name to TestA.
- Remove the statements and replace with an alert() that will let you know that the function can be called.
- Test.
- Declare a variable that define it to a regular expression that will find the letter A.
var TestA = /A/;
- Test that your variable works with an alert().
- Call the test() function on the form entry.
if (TestA.test(SimpleExample.Word.value))
{
Message = "There is an A in the Word textbox ";
}
- Show the Message in your alert()
Regular Expression Code
- In this exercise, we will use the test() function, which is built into JavaScript 1.2 and later.
- test() is a function available inside Regular Expression objects; so, the first thing you start with is a Regular Expression, which is a type of String object.
- First, we define and declare the Regular Expression.
var illegalChars = /\W/;
Start with / stuff /. All regular expressions are inside of two forward slashes.
Instead of trying to define every possible illegal characters, there are special predefined characters that represent groups of characters. W stands for the group of characters that aren't letters, numbers or underscores.
- Then we call the test function, which requires a String as an argument.
.
|