Transcript Slide 1

Regular Expressions and Pattern Matching
A Regular expression is a sequence or pattern
of characters that is matched against a string of
text when performing searches and
replacements.
The regular expression is normally delimited by
forward slashes, like /abc/.
They are used to verify data input on the client
side. Regular expressions are objects.
Literal Notation
FORMAT:
var variable_name = /regular expression/options;
EXAMPLE:
var class = /267/;
var prof = /Roberto/ig;
Constructor Method – RegExp()
• FORMAT
• var variable_name = new RegExp(“regular
expression”, “options”);
• EXAMPLES
• var class = new RegExp(“267”);
• var prof = new RegExp(“Roberto”, “ig”);
The test() Method
• Tests for a match in a string and returns
either true or false
EXAMPLE:
var myString = “She wants attention now!”;
var regex = /ten/;
regex.test(myString);
Regular Expression – Literal Way – E1
<html>
<head>
<title>Regular Expression Objects the Literal Way</title>
<script language = "JavaScript">
var myString="My gloves are worn for wear.";
var regex = /love/; // Create a regular expression object
if (regex.test(myString)){alert("Found pattern!");}
else{alert("No match.");}
</script>
</head>
<body></body>
</html>
Regular Expression – Constructor – E2
<html>
<head>
<title>Regular Expression Objects with the Constructor</title>
<script language = "JavaScript">
myString="My gloves are worn for wear.";
regex = new RegExp("love");
if (regex.test(myString)){alert("Found pattern love!");}
else {alert("No match.");}
</script>
</head>
<body></body>
</html>
The exec() Method
• Executes a search for a match in a string
and returns an array.
EXAMPLE:
list = /ring/.exec(“Don’t string me along, just
bring me the goods.”);
<html>
exec() – E3
<head>
<title>The exec() method</title>
<script language = "JavaScript">
var myString="My lovely gloves are worn for wear, Love.";
var regex = /love/i; // Create a regular expression object
var array=regex.exec(myString);
if (regex.exec(myString)){alert("Matched! " + array); }
else{alert("No match.");}
</script>
</head>
<body></body>
</html>
properties of RegExp object – E4
<html>
<head><title>The test() method</title></head>
<body bgcolor=silver>
<font face="arial" size="+1">
<script language = "JavaScript">
var myString="I love my new gloves!";
var regex = /love/g; // Create a regular expression object
var booleanResult = regex.test(myString);
if ( booleanResult != false ){
document.write("Tested regular expression <em>"+ regex.source + ".</em> The result is <em>"
+ booleanResult + "</em>");
document.write(".<br>Starts searching again at position " + regex.lastIndex + " in string<em> \"" +
RegExp.input + "\"<br>");
document.write("The last matched characters were: "+ RegExp.lastMatch+"<br>");
document.write("The substring preceding the last match is:" + RegExp.leftContext+"<br>");
document.write("The substring following the last match is:"+ RegExp.rightContext+"<br>");
}
else{ alert("No match!"); }
</script>
</body>
</html>
String methods – match() – E5
<html>
<head>
<title>The match() Method</title>
</head>
<body>
<font size="+1"><font face="arial, helvetica">
<script language = "JavaScript">
var matchArray = new Array();
var string="I love the smell of clover."
var regex = /love/g;
matchArray=string.match(regex);
document.write("Found "+ matchArray.length +" matches.<br>");
</script>
</body>
</html>
String methods – search() – E6
<html>
<head>
<title>The search() Method</title>
</head>
<body bgcolor="yellow">
<font size="+1">
<font face="arial, helvetica">
<script language = "JavaScript">
var myString="I love the smell of clover."
var regex = /love/;
var index=myString.search(regex);
document.write("Found the pattern "+regex+" at position "+index+"<br>");
</script>
</body>
</html>
String methods – replace() – E7
<html>
<head>
<title>The replace() Method</title>
</head>
<body bgcolor="yellow">
<font size="+1">
<font face="arial, helvetica">
<script language = "JavaScript">
var myString="Tommy has a stomach ache."
var regex = /tom/i; // Turn off case sensitivity
var newString=myString.replace(regex, "Mom");
document.write(newString +"<br>");
</script>
</body>
</html>
String methods – split() – E8
<html>
<head>
<title>The split() Method</title>
<font size="+1">
<font face="arial, helvetica">
<script language = "JavaScript">
var splitArray = new Array();
var string="apples:pears:peaches:plums:oranges"
var regex = /:/;
splitArray=string.split(regex); // Split the string by colons
for(i=0; i < splitArray.length; i++){document.write(splitArray[i] + "<br>");}
</script>
</head>
<body></body>
</html>
String methods – split() – E9
<html>
<head>
<title>The split() Method</title>
<font size="+1">
<font face="arial, helvetica">
<script language = "JavaScript">
var splitArray = new Array();
var myString="apples
pears,peaches:plums,oranges";
var regex = /[\t:,]/; // Delimeter is a tab, colon, or comma
splitArray=myString.split(regex);
for(i=0; i < splitArray.length; i++){document.write(splitArray[i] + "<br>");}
</script>
</head>
<body></body>
</html>
Metacharacters
• Metacharacters are characters that do not
represent themselves.
• If you have a backslash preceding a
metacharacter, the backslash turns off the
meaning of the metacharacters, but if you
have a backslash preceding an alphanumeric
character in a regular expression, then the
backslash is used to create a metasymbol.
Metacharacters – E10
EXAMPLE:
/^a…c/
EXPLANATION:
This regular expression contains metacharacters. The first one
is a caret (^). The caret matches for a string only if it is at the
beginning of the line. The period (.) is used to match for any
single character, including a white space. This expression
contains three periods, representing any three characters. To
find a literal period or any other character that does not
represent itself, the character must be preceded by a
backslash to prevent interpretation. The expression reads:
search at the beginning of the line for an a, followed by any
three single characters, followed by a c.
The dot metacharacter – E11
<html>
<head><title>The dot Metacharacter</title></head>
<body>
<script language="JavaScript">
var textString="Norma Jean";
var reg_expression = /N..ma/;
var result=reg_expression.test(textString);
document.write("<font size='+1'><b>"+result+"<br>");
if ( reg_expression.test(textString)){ // if ( result)
document.write("<b>The reg_ex /N..ma/ matched the string\""+
textString + "\".<br>");
}
else{document.write("No Match!");}
</script>
</body>
</html>
The character class – E12
<html>
<head><title>The Character Class</title></head>
<body>
<script language="JavaScript">
var reg_expression = /[A-Z][a-z]eve/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if ( result){
document.write("<b>The reg_ex /[A-Z][a-z]eve/ matched the string\""
+ textString +"\".<br>");
}
else{alert("No Match!");}
</script>
</body>
</html>
The character class – E13
<html>
<head><title>The Character Class</title></head>
<body>
<script language="JavaScript"> // Character class
var reg_expression = /[A-Za-z0-9_]/; // A single alphanumeric word character
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){
document.write("<b>The reg_ex /[A-Za-z0-9_]/ matched the string\""+
textString +"\".<br>");
}
else{ alert("No Match!");}
</script>
</body>
</html>
Negation within a character class – E14
<html>
<head><title>The Character Class and Negation</title></head>
<body>
<script language="JavaScript"> // Negation within a Character Class
var reg_expression = /[^0-9]/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The reg_ex /[^0-9]/ matched the string\""+
textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
The Digit Metasymbol – E15
<html>
<head><title>The Digit Meta Symbol</title></head>
<body>
<script language="JavaScript">
var reg_expression = /6\d\d/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /6\\d\\d/ matched the
string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
The Digit Metasymbol Negated – E16
<html>
<head><title>The Digit Meta Symbol Negated</title></head>
<body>
<script language="JavaScript">
var reg_expression = /[a-z]\D\D/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /[a-z]\\D\\D/
matched the string\"" + textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Word and Space Metasymbols – E17
<html>
<head><title>Word and Space Metasymbols</title></head>
<body>
<script language="JavaScript">
var reg_expression = /\w\s\w\W/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /\w\s\w\W/ matched
the string\"" + textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: ?(0 or 1) –E18
In this example, we need at least two consecutive digits or one digit, a period and
another digit, to have a match .
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /\d\.?\d/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /\\d\\.?\\d/ matched the
string\""+textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: *(0 or more) –E19
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /[A-Z][a-z]*\s/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /[A-Z][a-z]*\\s/
matched the string"+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: +(1 or more) –E20
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /[A-Z][a-z]+\s/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /[A-Z][a-z]+\\s/
matched the string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: {m,n}(at least m, no
more than n) –E21
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /abc\d{1,3}\.\d/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /[A-Z][a-z]+\\s/ matched the
string\""+ textString +"\".<br>");}
else{ alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: {m}(exact m) –E22
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /#\d{5}\.\d/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /#\\d{5}\\.\\d/ matched the string ""+
textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Metacharacters to repeat pattern: {m,}(at least m) –E23
<html>
<head><title></title></head>
<body>
<script language="JavaScript">
var reg_expression = /5{1,}\.\d/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /#\\d{5}\\.\\d/ matched the
string \""+ textString
+"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Replace() with “greediness” – E24
<html>
<head><title>Greed</title></head>
<body bgcolor=lightblue>
<script language="JavaScript">
var myString="abcdefghijklmnopqrstuvwxyz";
document.write("<font size='+1'>Old string:<b> "+myString+"<br>");
myString=myString.replace(/[a-z]+/, "XXX");
document.write("</b>New string:<b> "+ myString+"<br>");
</script>
</body>
</html>
Turning off “greediness” - ? – E25
<html>
<head><title>Greed</title></head>
<body bgcolor=lightblue>
<script language="JavaScript">
var myString="abcdefghijklmnopqrstuvwxyz";
document.write("<font size='+1'>Old string: <b> "+ myString
+"<br>");
myString=myString.replace(/[a-z]+?/, "XXX");
document.write("</b>New string:<b> "+ myString+"<br>");
</script>
</body>
</html>
Beginning of line ^ - E26
<html>
<head><title>Beginning of Line Anchor</title></head>
<body>
<script language="JavaScript">
var reg_expression = /^Will/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /^Will/ matched the string\""+
textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Beginning of line ^ - E27
<html>
<head><title>Beginning of Line Anchor</title></head>
<body>
<script language="JavaScript">
var reg_expression = /^[JK]/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /^[JK]/ matched the
string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
<html>
End of line - $ - E28
<head><title>Beginning of Line Anchor</title></head>
<body>
<script language="JavaScript">
var reg_expression = /50$/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /50$/ matched the
string\""+ textString
+"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Anchors – E29
<html>
<head><title>Anchors</title></head>
<body>
<script language="JavaScript">
var reg_expression = /^[A-Z][a-z]+\s\d$/;
var string=prompt("Enter a name and a number","");
if ( reg_expression.test(string)){alert("It Matched!!"); }
else{alert("No Match!");}
</script>
</body>
</html>
Word Boundary Anchors \b – E30
<html>
<head><title>Beginning of Line Anchor</title></head>
<body>
<script language="JavaScript">
var reg_expression = /\blove\b/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /\\blove\\b/ matched
the string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Alternation – E31
<html>
<head><title>Alternation</title></head>
<body>
<script language="JavaScript">// Alternation: this or that or whatever...
var reg_expression = /Steve|Dan|Tom/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /Steve|Dan|Tom/
matched the string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Grouping or clustering – E32
<html>
<head><title>Grouping or Clustering</title></head>
<body>
<script language="JavaScript">// Grouping with parentheses
var reg_expression = /^(Sam|Dan|Tom) Robbins/;
var textString=prompt("Type a string of text","");
var result=reg_expression.test(textString); // Returns true or false
document.write("<font size='+1'><b>"+result+"<br>");
if (result){document.write("<b>The regular expression /^(Sam|Dan|Tom)
Robbins/ matched the string\""+ textString +"\".<br>");}
else{alert("No Match!");}
</script>
</body>
</html>
Capturing – E33
If the regular expression pattern is enclosed in parentheses, a subpattern is created.
<html>
<head><title>Capturing</title></head>
<body>
<script language="JavaScript">
textString = "Everyone likes William Rogers and his friends."
var reg_expression = /(William)\s(Rogers)/;
myArray=textString.match(reg_expression);
document.write(myArray); // Three element array
alert(RegExp.$1 + " "+RegExp.$2);
// alert(myArray[1] + " "+ myArray[2]);
// match and exec create an array consisting of the string, and
// the captured patterns. myArray[0] is "William Rogers"
// myArray[1] is "William" myArray[2] is "Rogers".
</script>
</body>
</html>
Capture and Replace – E34
<html>
<head><title>Capture and Replace</title>
<font size="+1"><font face="helvetica">
<script language = "JavaScript">
var string="Tommy Savage:203-123-4444:12 Main St."
var newString=string.replace(/(Tommy) (Savage)/, "$2, $1");
document.write(newString +"<br>");
</script>
</head>
<body></body>
</html>
Capture and Replace – E35
<html>
<head><title>Capture and Replace</title>
<font size="+1"><font face="helvetica">
<script language = "JavaScript">
var string="Tommy Savage:203-123-4444:12 Main St."
var newString=string.replace(/(\w+)\s(\w+)/, "$2, $1");
document.write(newString +"<br>");
</script>
</head>
<body></body>
</html>
Checking for empty fields – E36
<html>
<head>
<title>Checking for Empty Fields</title>
<script language="JavaScript">
function validate_text(form1) {
if ( form1.user_name.value == "" || form1.user_name.value == null){
alert("You must enter your name.");
return false;
}
if ( form1.user_phone.value == "" || form1.user_phone.value == null){
alert("You must enter your phone.");
return false;
}
else {return true;}
}
</script>
</head>
<body>
<h2> Checking for Empty fields </h2>
<form name="formtest" action="/cgi-bin/form1.cgi" method="get" onSubmit="return validate_text(formtest)">
Please enter your name: <br>
<input type="text" size=50 name="user_name">
<p>Please enter your phone number: <br>
<input type="text" size=30 name="user_phone">
<p>
<input type=submit value="Send">
<input type=reset value="Clear">
</form>
</body>
</html>
Checking for Numeric ZIP Codes – E37
<html>
<head><title>Testing for a Valid Zip Code</title>
<script language="JavaScript">
function ok_Zip(zip){
var regex=/^\d{5}$/; // Match for 5 numbers
if ( regex.test(zip.value) == false) {
alert("Zipcode must contain exactly five numbers!");
zip.focus();
return false;
}
if ( zip.value == ""){
alert("You must enter a zipcode");
zip.focus();
return false;
}
return true;
}
</script>
</head>
<body><font face="arial" size="+1">
<form name="ZipTest" action="/error" >
Enter your zip code:
<input type="text" name="zipcode" size=5>
<input type="button" value="Check zip" onClick="if( ok_Zip(ZipTest.zipcode)) {alert('Zip is valid.')}">
<br><input type="reset">
</form>
</body>
</html>
Checking for Alphabetic Data – E38
<html>
<head><title>Testing for a Alphabetic Characters</title>
<script language="JavaScript">
function okAlpha(form){
var regex=/^[a-zA-Z]+$/; // match for upper or lowercase letters
if ( regex.test(form.fname.value) == false) {
alert("First name must contain alphabetic characters!");
form.fname.focus();
return false;
}
if ( form.fname.value == ""){
alert("You must enter your first name.");
form.fname.focus();
return false;
}
return true;
}
</script>
</head>
<body><font face="arial" size="+1">
<form name="alphaTest" method="post" action="/cgi-bin/testing.pl" onSubmit="return okAlpha(this)" >
Enter your first name:
<input type="text" name="fname" size=20>
•
<p>
•
<input type="submit" value="Submit">
•
<input type="reset">
•
</form>
•
</body>
•
</html>
Removing Characters – E39
<html>
<head>
<title>Removing Spaces and Dashes</title>
</head>
<body bgcolor="magenta">
<font size="+1" font face="arial">
<h2>Removing Spaces and Hyphens</h2>
<script language = "JavaScript">
var string="444- 33 - 12 34"
var regex = /[ -]+/g;
var newString=string.replace(regex, "");
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
</script>
</body>
</html>
Removing Parentheses, Spaces and Dashes –
E40
<html>
<head><title>Removing Paraens</title></head>
<body bgcolor="magenta">
<font size="+1">
<font face="arial">
<h2>Removing Unwanted Parentheses, Spaces, and Dashes</h2>
<script language = "JavaScript">
var string="(408)-332-1 234"
var regex = /[() -]+/g;
var newString=string.replace(regex, "");
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
</script>
</body>
</html>
Removing any non-digits – E41
<html>
<head><title>Removing all Non-digits</title></head>
<body bgcolor="magenta">
<font size="+1" face="arial">
<h3>If it's not a number, remove it!</h2>
<script language = "JavaScript">
var string="phone is (408)-//[332]-1234@#!!!"
var newString=string.replace(/\D/g, "");
document.write("The original string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
</script>
</body>
</html>
Removing any non-alphanumeric – E42
<html>
<head><title>Removing Non-AlphaNumeric Characters</title></head>
<body bgcolor="magenta">
<font size="+1">
<font face="arial">
<h3>If it's not a number or a letter, remove it!</h2>
<script language = "JavaScript">
var string="(408)-//[332]-1234@#!!!"
var newString=string.replace(/\W/g, "");
document.write("The orginal string: "+string);
document.write("<br>The new string: "+ newString +"<br>");
</script>
</body>
</html>
Checking for Valid SS # - E43
<html>
<head><title>Testing for a Social Security Number</title>
<script language="JavaScript">
function okSocial(sform){
var regex=/^\d{3}-?\d\d-?\d{4}$/;
if ( regex.test(sform.ssn.value) == false) {
alert("Social security number invalid!");
sform.ssn.focus();
return false;
}
if ( sform.ssn.value == ""){
alert("Please enter your social security number.");
sform.ssn.focus();
return false;
}
return true;
}
</script>
</head>
<body><font face="arial" size="+1">
<center>
<form name="snnTest" method=post action="/cgi-bin/testing" onSubmit="return okSocial(this)" >
Enter your social security number: xxx-xx-xxxx
<p>
<input type="text" name="ssn" size=11>
<p>
<input type="submit" value="Submit">
<input type="reset">
</form>
</body>
</html>
Checking for valid phone # - E44
<html>
<head><title>Validating Phone Numbers</title>
<script language="JavaScript">
function ok_Phone(phform){
var regex = /^\(?\d{3}\)?-?\s*\d{3}\s*-?\d{4}$/;
if(regex.test(phform.user_phone.value)){return true;}
else{
alert("Enter a valid phone number");
return false;
}
}
</script>
</head><hr>
<body><h2>
Checking for a Valid Phone Number </h2>
<form name="formtest" action="http://localhost/cgi-bin/environ.pl" method="post"
onSubmit="return ok_Phone(this);">
<p>
Please enter your phone: <BR>
<input type="text" size=40 name="user_phone">
<p>
<input type=submit value="Submit">
<input type=reset value="Clear">
</form>
</body>
</html>
Checking for valid e-mail addresses – E45
<html>
<head><title>Validating E-Mail Addresses</title>
<script language="JavaScript">
function ok_Email(eform){
var regex = /^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/;
if(regex.test(eform.user_email.value)){return true;}
else{
alert("Enter a valid email address");
return false;
}
}
</script>
</head><hr>
<body>
<h2> Checking for Valid Email Address </h2>
<form name="formtest" action="http://localhost/cgi-bin/environ.pl" method="post“
onSubmit="return ok_Email(this);">
<p>
Please enter your email address: <BR>
<input type="text" size=40 name="user_email">
<p>
<input type=submit value="Send">
</form>
</body>
</html>
Credit Card Validation - Expiration Date – E46
<html>
<head>
<title>Testing Expiration Dates</title>
<script language="javascript">
function validExpire(form) {
var now = new Date();
var thismonth = (now.getMonth() + 1);
var thisyear = now.getFullYear() ;
var expireYear = parseInt(form.expireYear.value);
var yearLength = form.expireYear.value.length;
var expireMonth = parseInt(form.expireMonth.value);
if( yearLength == 2 ){expireYear += 2000;}
if ((expireMonth < thismonth && expireYear == thisyear) || expireMonth > 12){
alert("Invalid month");
return false;
}
else if ( expireYear < thisyear) {
alert("Invalid year");
return false;
}
else {return true;}
}
</script>
</head>
<body>
<form name="myForm" action="http://127.0.0.1/cgi-bin/env.cgi" onSubmit="return validExpire(this)">
<p>Enter the month (02 or 2):
<input name="expireMonth" type="text" size=5>
<p>Enter the year (2003 or 03):
<input name="expireYear" type="text" size=5>
<input type="submit" value="submit">
<input type="reset" value="clear">
</form>
</body>
</html>
<html>
Credit Card Validation – Type, Prefix and
Length – E47
<head>
<title>Checking for Valid CC Type and Length</title>
<script language="JavaScript">
function checkCC(myForm){
var cc_type;
var cc_length;
if (myForm.select1.selectedIndex==0){cc_type="Visa";}
else if( myForm.select1.selectedIndex==1){cc_type="MasterCard";}
else if( myForm.select1.selectedIndex==2){cc_type="Discover";}
else {alert("You didn't select a card type.");}
cc_length=myForm.text.value.length;
switch(cc_type){
case "Visa" :
if ( cc_length == 13 || cc_length == 16){return true;}
else{
alert("Invalid length");
return false;
}
break;
case "MasterCard":
if ( cc_length == 16){return true;}
else{
alert("Invalid length");
return false;
}
break;
case "Discover":
if ( cc_length == 16){return true;}
else{
alert("Invalid length");
return false;
}
break;
default:
alert("Invalid type");
return false;
break;
}
}
</script>
</head>
<body bgcolor="lightblue">
<font size="+1" face="arial">
<form name="form1" onSubmit="return checkCC(this);">
Please select a credit card from the menu:
<p>
<select name="select1" size="3">
<option value="Visa">Visa</option>
<option value="MC">MasterCard</option>
<option value="Dis">Discover</option>
</select>
<p>
Please enter your card number:
<p>
<input type=textbox name="text" size=30>
<p>
<input type=submit value="Check card">
<input type=reset>
</form>
</body>
</html>
Putting all together – E48
<html>
<head><title>Validating a Form</title>
<script language="JavaScript">
function ok_Email(emform){
var regex=/^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/;
if(regex.test(eform.user_email.value)){return true;}
else{
alert("Enter a valid email address");
return false;
}
function ok_Phone(phform){
var regex = /^\(?\d{3}\)?-?\s*\d{3}\s*-?\d{4}$/;
if(regex.test(phform.value)){return true;}
else{return false;}
}
function ok_Form(myform){
if (ok_Email(myform.user_email)== false){
alert( "Invalid email address");
myform.user_email.focus();
myform.user_email.select();
return false;
}
if (ok_Phone(myform.user_phone) == false){
alert( "Invalid phone number");
myform.user_phone.focus();
myform.user_phone.select();
return false;
}
return true;
}
</script>
</head><hr>
<body bgcolor="lightgreen"> <font face="arial" size="+1">
<h2> Checking Form Input</h2>
<form name="myform"
action="http://localhost/cgi-bin/environ.pl" method="post"
onSubmit="return ok_Form(this);">
<p>
Please enter your email address: <BR>
<input type="text" size=40 name="user_email">
<p>
Please enter your phone number: <BR>
<input type="text" size=12 name="user_phone">
<p>
<input type=submit value="Send">
</form>
</body>
</html>