Web Systems Technologies Chapter 16 Clientside Validation Regular

  • Slides: 44
Download presentation
Web Systems & Technologies Chapter 16 – Client-side Validation, Regular Expressions, and Server-side Validation

Web Systems & Technologies Chapter 16 – Client-side Validation, Regular Expressions, and Server-side Validation 1

Validating User Input with Java. Script § Ensure that data is complete and correct

Validating User Input with Java. Script § Ensure that data is complete and correct before submission. § Types of Java. Script validations: • Checking that fields are not empty • Ensuring that email addresses conform to the proper format • Ensuring that values entered are within expected bounds 2

Example 16 -1. A form with Java. Script validation (part 1) <!DOCTYPE html> <head>

Example 16 -1. A form with Java. Script validation (part 1) <!DOCTYPE html> <head> <title>An Example Form</title> <style>. signup { border: 1 px solid #999999; font: normal 14 px helvetica; color: #444444; } </style> 3

Example 16 -1. A form with Java. Script validation (part 1) <script> function validate(form)

Example 16 -1. A form with Java. Script validation (part 1) <script> function validate(form) { fail = validate. Forename(form. forename. value) fail += validate. Surname(form. surname. value) fail += validate. Username(form. username. value) fail += validate. Password(form. password. value) fail += validate. Age(form. age. value) fail += validate. Email(form. email. value) if (fail == "") return true else { alert(fail); return false } } </script> 4

Example 16 -1. A form with Java. Script validation (part 1) </head> <body> <table

Example 16 -1. A form with Java. Script validation (part 1) </head> <body> <table class="signup" border="0" cellpadding="2“ cellspacing="5" bgcolor="#eeeeee"> <th colspan="2" align="center"> Signup Form</th> <form method="post" action="adduser. php" onsubmit="return validate(this)"> 5

Example 16 -1. A form with Java. Script validation (part 1) <tr><td>Forename</td> <td><input type="text"

Example 16 -1. A form with Java. Script validation (part 1) <tr><td>Forename</td> <td><input type="text" maxlength="32" name="forename"></td></tr> <tr><td>Surname</td> <td><input type="text" maxlength="32" name="surname"></td></tr> <tr><td>Username</td> <td><input type="text" maxlength="16" name="username"></td></tr> <tr><td>Password</td> <td><input type="text" maxlength="12" name="password"></td></tr> <tr><td>Age</td> 6

Example 16 -1. A form with Java. Script validation (part 1) <td><input type="text" maxlength="3"

Example 16 -1. A form with Java. Script validation (part 1) <td><input type="text" maxlength="3" name="age"> </td></tr> <tr><td>Email</td> <td><input type="text" maxlength="64" name="email"> </td></tr> <tr><td colspan="2" align="center"> <input type="submit“ value="Signup"></td></tr> </form> </table> </body> </html> 7

Figure 16 -1. The output from Example 16 -1 8

Figure 16 -1. The output from Example 16 -1 8

A form with Java. Script validation § The function validate calls up six other

A form with Java. Script validation § The function validate calls up six other functions to validate each of the form’s input fields. • Each of these functions returns empty string if a field validates or an error message otherwise. • The validate function returns true if there are no errors. • If there any errors, the script shows an alert box with respective error messages and returns false. § If validate returns false, the form is prevented from being submitted. Otherwise, the form is allowed to be submitted. • on. Submit is used to call a function when the form is submitted. • That function can return a value of either true or false to signify whether the form should be allowed to be submitted. 9

Validating the forename and surname § validate. Forename checks the value of the forename

Validating the forename and surname § validate. Forename checks the value of the forename passed as parameter. § If this value is the empty string, an error message is returned. § If there is any input, an empty string is returned to signify that no error was encountered. § If the user entered spaces in place of forename, it would be accepted by validate. Forename. § The validate. Surname function is identical to validate. Forename. 10

Validating the forename and surname function validate. Forename(field) { return (field == "") ?

Validating the forename and surname function validate. Forename(field) { return (field == "") ? "No Forename was entered. n" : "" } function validate. Surname(field) { if (field == "") return "No Surname was entered. n" else return "" } 11

Validating the username § validate. Username ensure that usernames contains only characters of a-z,

Validating the username § validate. Username ensure that usernames contains only characters of a-z, A-Z, 0 -9, _ and -, and the length is at least five characters long. • The if. . . else statements starts by returning an error if field is empty. • Further it checks if username is less than five characters in length, another error message is returned. • Lastly, Java. Script test function is called, passing a regular expression to be matched against field. Even if one character is not acceptable, the test function returns true. So, validate User returns an error string. 12

Validating the username function validate. Username(field) { if (field == "") return "No Username

Validating the username function validate. Username(field) { if (field == "") return "No Username was entered. n" else if (field. length < 5) return "Usernames must be at least 5 characters. n" else if (/[^a-z. A-Z 0 -9_-]/. test(field)) return "Only a-z, A-Z, 0 -9, - and _ allowed in Usernames. n" return "" } 13

Breakdown of the validate. Username regular expression 14

Breakdown of the validate. Username regular expression 14

Validating the password § First the function checks and returns an error if field

Validating the password § First the function checks and returns an error if field is empty. § Next, an error message is returned if a password is shorter than six characters. § Passwords must have at least one each of a lowercase, uppercase, and numerical character. § Test function with regular expression is called three times for each of three cases. If any one of them returns false, an error message is returned. Otherwise, the empty string is returned to signify that the password was OK. 15

Validating the password function validate. Password(field) { if (field == "") return "No Password

Validating the password function validate. Password(field) { if (field == "") return "No Password was entered. n“ else if (field. length < 6) return "Passwords must be at least 6 characters. n" else if (!/[a-z]/. test(field) || ! /[A-Z]/. test(field) || !/[0 -9]/. test(field)) return "Passwords require one each of a-z, A-Z and 0 -9. n" return "" } 16

Validating the age § validate. Age returns an error message if field is not

Validating the age § validate. Age returns an error message if field is not a number (determined by a call to the is. Na. N function), or if the age entered is lower than 18 or greater than 110. function validate. Age(field) { if (is. Na. N(field)) return "No Age was entered. n" else if (field < 18 || field > 110) return "Age must be between 18 and 110. n" return "" } 17

Validating the email § First it is checked that email field is not empty.

Validating the email § First it is checked that email field is not empty. § Then a check is made to ensure there is a period (. ) somewhere from at least the second character of the field, and that an @ symbol appears somewhere at or after the second character. § Lastly, the test function is called to see whether any disallowed characters appear in the field. The allowed characters in an email address are uppercase and lowercase letters, numbers, and the _, -, period, and @ characters, as given in the regular expression passed to the test method. § If no errors are found, the empty string is returned to indicate successful validation. 18

Validating the email function validate. Email(field) { if (field == "") return "No Email

Validating the email function validate. Email(field) { if (field == "") return "No Email was entered. n" else if (!((field. index. Of(". ") > 0) && (field. index. Of("@") > 0)) || /[^a-z. A-Z 0 -9. @_-]/. test(field)) return "The Email address is invalid. n" return "" } 19

Figure 16 -2. Java. Script form validation in action 20

Figure 16 -2. Java. Script form validation in action 20

Regular Expressions § Regular expressions are used to construct powerful pattern-matching algorithms within a

Regular Expressions § Regular expressions are used to construct powerful pattern-matching algorithms within a single expression. § Pattern can be used for text search and text replace operations. § Every regular expression must be enclosed in slashes (/). § Metacharacters - characters having special meanings, e. g. asterisk (*) and plus (+) • Example: Search for a name John Doe separated by any number of spaces or no space. • /John *Doe/ 21

Fuzzy Character Matching § The dot (. ) can match anything except a newline.

Fuzzy Character Matching § The dot (. ) can match anything except a newline. § Example: search for HTML tags, which start with < and end with >. • /<. *>/ • “Match anything that lies between < and >, even if there’s nothing. ” • It matches <>, <em>, , and so on. § To avoid empty case, <>, use + instead of *, like this: • /<. +>/ • “Match anything that lies between < and > as long as there’s at least one character between them. ” • It matches <em>, </em>, <h 1>, </h 1>, tags with attributes <a href="www. abc. xyz">, and will keep matching upto the last > on the line like <h 1><b>Introduction</b></h 1> 22

Fuzzy Character Matching § To match the dot character itself (. ), escape it

Fuzzy Character Matching § To match the dot character itself (. ), escape it by placing a backslash () before it. § Example: match the floating-point number 5. 0 • /5. 0/ § Example: to allow any number of zeros after decimal point, add an asterisk: • /5. 0*/ 23

Grouping Through Parentheses § Use parentheses to group characters on which metacharacters need to

Grouping Through Parentheses § Use parentheses to group characters on which metacharacters need to be applied. § Example: match increment in power by one thousand e. g. , 1, 000, 000 … • /1(, 000)+ / • “Match 1 followed by one or more complete groups of a comma followed by three zeros”. • The space after the + character indicates that the match must end when a space is encountered. Without it, 1, 000, 00 would incorrectly match because only the first 1, 000 would be taken into account, and the remaining , 00 would be ignored. 24

Character Classes § Group of characters placed inside square brackets [] are called a

Character Classes § Group of characters placed inside square brackets [] are called a character class. § Character class matches a single character from a list of characters. § Example: match both the American spelling gray and the British spelling grey • /gr[ae]y/ § Indicating a Range • Use a hyphen (-) to indicate a range inside brackets. • Example: match a single digit /[0 -9]/ § Negation • Place a caret (^) after the opening bracket to negate the whole class. • Example: match a followed by not b or c /a[^bc]/ 25

Example – match HTML tag § /<[^>]+>/ • / opening slash that indicates this

Example – match HTML tag § /<[^>]+>/ • / opening slash that indicates this is a regular expression. • < opening bracket of an HTML tag. This is matched exactly; it’s not a metacharacter. • [^>] character class. The embedded ^> means “match anything except a closing angle bracket. ” • + allows any number of characters to match the previous [^>], as long as there is at least one of them. • > closing bracket of an HTML tag. This is matched exactly. • / closing slash that indicates the end of the regular expression. 26

General Modifiers § /g enables global matching • Specify this modifier to replace all

General Modifiers § /g enables global matching • Specify this modifier to replace all matches, rather than only the first one. § /i enables case-insensitive matching • Instead of /[a-z. AZ]/ specify /[a-z]/i or /[A-Z]/i. § /m enables multiline mode, in which the caret (^) and dollar sign ($) match before and after any newlines in the subject string. § Example: match both occurrences of the word cats in the sentence “I like cats, and Ca. Ts like me”. • /cats/gi 27

Using Regular Expressions in Java. Script § Two methods: 1. Test – returns true

Using Regular Expressions in Java. Script § Two methods: 1. Test – returns true if its argument matches the regular expression 2. Replace - takes a second parameter: the string to replace the text that matches and returns replaced string as new string § Example: does the word cats appears at least once somewhere within the string? • document. write(/cats/i. test("Cats are funny. I like cats. ")) § Example: Replaces any occurrences of the word cats with the word dogs, printing the result. • str = "Cats are friendly. I like cats. " • document. write(str. replace(/cats/gi, "dogs")) 28

Using Regular Expressions in PHP § Most common regular expression functions in PHP are:

Using Regular Expressions in PHP § Most common regular expression functions in PHP are: preg_match, preg_match_all, and preg_replace. § preg_match() • Searches string for pattern, returning true (1) if pattern exists, and false (0) otherwise. • The first argument is regular expression, second is text to match, and third argument shows what text matched. • Example: does the word cats appears at least once somewhere within the string? $n = preg_match("/cats/i", "Cats are crazy. I like cats. "); 29

Using Regular Expressions in PHP § preg_match() • Example: Where does the word cats

Using Regular Expressions in PHP § preg_match() • Example: Where does the word cats appears at least once somewhere within the string? $n = preg_match("/cats/i", "Cats are curious. I like cats. ", $match); echo "$n Matches: $match[0]"; • The third argument is an array. The function puts the matching text as the first element of the array. • In this example, the output lets us know that the matched text was capitalized: 1 Matches: Cats 30

Using Regular Expressions in PHP § preg_match_all() • Searches for all occurrences of the

Using Regular Expressions in PHP § preg_match_all() • Searches for all occurrences of the pattern in the string. • The third argument is an array. The function puts the matching text as the sub-array(s) of the first element. • Example: $n = preg_match_all("/cats/i", "Cats are strange. I like cats. ", $match); echo "$n Matches: "; for ($j=0 ; $j < $n ; ++$j) echo $match[0][$j]. " "; Output: 2 Matches: Cats cats 31

Using Regular Expressions in PHP § preg_replace() • Searches for all occurrences of the

Using Regular Expressions in PHP § preg_replace() • Searches for all occurrences of the pattern in the string and replaces them with user’s specifies string. • Example: replace all occurrences of the word cats with the word dogs, regardless of case. echo preg_replace("/cats/i", "dogs", "Cats are furry. I like cats. "); Output: dogs are furry. I like dogs. 32

Redisplaying a Form After PHP Validation § HTML document validate. html sends data to

Redisplaying a Form After PHP Validation § HTML document validate. html sends data to the PHP program adduser. php, but only if Java. Script validates the fields or if Java. Script is disabled or unavailable. § adduser. php receives the posted form, perform its own validation, and then present the form again to the visitor if the validation fails. • HTML from Example 16 -1 has been repeated in the PHP code within an <<<_END. . . _END; structure • It displays the form with the values that the visitor entered the previous time using the value parameter of each <input> tag (such as value="$forename"). 33

Example 16 -3. The adduser. php program <? php // adduser. php $forename =

Example 16 -3. The adduser. php program <? php // adduser. php $forename = $surname = $username = $password = $age = $email = ""; if (isset($_POST['forename'])) $forename = fix_string($_POST['forename']); if (isset($_POST['surname'])) $surname = fix_string($_POST['surname']); if (isset($_POST['username'])) $username = fix_string($_POST['username']); if (isset($_POST['password'])) $password = fix_string($_POST['password']); 34

Example 16 -3. The adduser. php program if (isset($_POST['age'])) $age = fix_string($_POST['age']); if (isset($_POST['email']))

Example 16 -3. The adduser. php program if (isset($_POST['age'])) $age = fix_string($_POST['age']); if (isset($_POST['email'])) $email = fix_string($_POST['email’]); $fail = validate_forename($forename); $fail. = validate_surname($surname); $fail. = validate_username($username); $fail. = validate_password($password); $fail. = validate_age($age); $fail. = validate_email($email); 35

Example 16 -3. The adduser. php program echo "<!DOCTYPE html>n<html><head><title>An Example Form</title>"; if ($fail

Example 16 -3. The adduser. php program echo "<!DOCTYPE html>n<html><head><title>An Example Form</title>"; if ($fail == "") { echo "</head><body>Form data successfully validated: $forename, $surname, $username, $password, $age, $email. </body></html>"; // This is where you would enter the posted fields into a database, exit; } echo <<<_END // heredoc multiline string 36

Example 16 -3. The adduser. php program <!-- The HTML/Java. Script section --> <style>.

Example 16 -3. The adduser. php program <!-- The HTML/Java. Script section --> <style>. signup { border: 1 px solid #999999; . . </form> </table> </body> </html> _END; 37

Example 16 -3. The adduser. php program // The PHP functions function validate_forename($field) {

Example 16 -3. The adduser. php program // The PHP functions function validate_forename($field) { return ($field == "") ? "No Forename was entered ": ""; } function validate_surname($field) { return($field == "") ? "No Surname was entered " : ""; } 38

Example 16 -3. The adduser. php program function validate_username($field) { if ($field == "")

Example 16 -3. The adduser. php program function validate_username($field) { if ($field == "") return "No Username was entered "; else if (strlen($field) < 5) return "Usernames must be at least 5 characters "; else if (preg_match("/[^a-z. A-Z 0 -9_-]/", $field)) return "Only letters, numbers, - and _ in usernames "; return ""; } 39

Example 16 -3. The adduser. php program function validate_password($field) { if ($field == "")

Example 16 -3. The adduser. php program function validate_password($field) { if ($field == "") return "No Password was entered "; else if (strlen($field) < 6) return "Passwords must be at least 6 characters "; else if (!preg_match("/[a-z]/", $field) || !preg_match("/[A-Z]/", $field) || !preg_match("/[0 -9]/", $field)) return "Passwords require 1 each of a-z, A-Z and 0 -9 "; return ""; } 40

Example 16 -3. The adduser. php program function validate_age($field) { if ($field == "")

Example 16 -3. The adduser. php program function validate_age($field) { if ($field == "") return "No Age was entered "; else if ($field < 18 || $field > 110) return "Age must be between 18 and 110 "; return ""; } 41

Example 16 -3. The adduser. php program function validate_email($field) { if ($field == "")

Example 16 -3. The adduser. php program function validate_email($field) { if ($field == "") return "No Email was entered "; else if (!((strpos($field, ". ") > 0) && (strpos($field, "@") > 0)) || preg_match("/[^a-z. A-Z 0 -9. @_-]/", $field)) return "The Email address is invalid "; return ""; } 42

Example 16 -3. The adduser. php program function fix_string($string) { if (get_magic_quotes_gpc()) $string =

Example 16 -3. The adduser. php program function fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return htmlentities ($string); } ? > § the fix_string function is used to sanitize each field and prevent code injection. § get_magic_quotes_gpc() is deprecated and should use filter_input 43

Figure 16 -5. The form as represented after PHP validation fails 44

Figure 16 -5. The form as represented after PHP validation fails 44