Performing Validations in an HTML Web Page

Performing Validations in an HTML Web Page

Your first line of defense in the world of the Internet is your HTML page. You can use controls that assist the user not only in entering information but also in entering it in the correct format. For example, you can use HTML elements like list boxes and radio buttons to provide the user with a limited range of options to choose from.

Although using HTML-based Web pages is not an effective method for performing complex validations, you can perform simple validations. Some of these validations and their solutions are listed below:

  • Restricting the value that a user can enter to a group of values by using radio buttons

  • Restricting the size of the information that a user can enter by using the SIZE attribute

  • Restricting the value that a user can enter to a group of values by using radio buttons

  • Restricting the size of the value that a user can enter in a text box by using the MAXLENGTH attribute

  • Restricting the values that a user can enter to a range of values by using a list box

However, there are certain actions or validations that are beyond the control of HTML. For example, you might want the user to only enter numeric values in a particular field or want the date to appear in a particular format. You might want a user to enter information from a specific range of values only. None of these validations is possible by using HTML. To perform these validations you need to write a code in a scripting language, such as VBScript, JavaScript, or PHP, to name a few. Let’s learn how you can make these validations possible in PHP.

Performing Validations in PHP
You have learned to validate the user’s input at the basic level in HTML. There you learned how to check the size of the input and set the maximum number of characters the field will accept. However, you still need to ensure that the data that has been entered by the user conforms to specified standards.

Something that you need to remember here is that users should get the opportunity to correct any mistakes they make in the form instead of receiving an error message when the database is unable to process the query. For this reason you need to check the content before the information is passed to the database server.

PHP provides numerous functions to validate information entered in an input field. These functions can be generally divided into three categories based on the types of information that a user mostly enters. These validation categories include:

Validating string information

Validating date information

Validating integer information

Let me first explain how you can validate string information.

Validating String Information
The most common validation requirement is for checking string information. You can use string functions to validate string information. You learned about a few of these functions in Chapter 9, “HTML Basics.” These functions were isempty(), strlen(), and strcmp(). As you might recall, the isempty() function is used to check whether a string variable doesn’t contain any value, while strlen() and the strcmp() functions are used to check if the length of the string is more than or less than the required length or if the content of two strings is similar to each other.

Let’s now look at these and some of the other functions that are available in PHP.

The count_chars() Function
This function is used to retrieve information about the characters that are used in the string:

$intvar = count_chars(string strvar [, mode])

The function returns a mixed variable and is used to count the number of occurrences of a character in a string.

The ltrim() Function
This function is used to remove the whitespaces from the beginning of a string. You can use this function to determine if a user has entered spaces instead of valid information. The syntax of the function is as given below.

$strval = ltrim(string strvar [, string charlist])
The second parameter is optional. If the second parameter is not specified, the above code will remove all the whitespaces, tabs, line feed characters, NULL value, and a carriage return from the entered information. (These characters appear as shown in Table 20-1.) You can include these characters in the second parameter to keep these values. You can use the . character to specify multiple values.

Table 20-1: Characters and Their Values Value
Character

Tab character
“\t”

Whitespace
“ “

Carriage return
“\r”

Line feed
“\n”

Vertical tab
“\xOB”

NULL
“\0”

The rtrim() Function
This function is similar to the trim() function. However, it removes whitespaces from the end of a string. The syntax of the function is as given below.

$strval = rtrim(string strvar [, string charlist])

The second parameter is optional and can contain any of the values specified in Table 20-1.

The trim() Function
This function is used to extract all the empty spaces from the beginning and end of a string, storing the result into another string. The syntax of the function is as given below.

$Intval = strspn (string strvar1, string $strvar2)
The second parameter is optional, and you can use it to specify characters that the function should not exclude from the result. If this parameter is not specified, the function will remove all spaces and these special characters. The list of these characters appears in Table 20-1.

The chop() Function
This function is similar to the rtrim() function and is used to extract whitespaces and special characters from the right of the string.

The similar_text() Function
You use this function to compare two string values and retrieve similar characters between them. The syntax of the function is as given below.

$Intval = similar_text(string firststr, string secondstr [,
float percent])
In the above code, firststr is compared to secondstr and returns the number of common characters in both the strings. If the third parameter is specified, the return value contains the amount of similarity in percentage.

The strcasecmp() Function
This function is used to perform a binary comparison of two strings and return the number of similar characters, storing it in an integer variable. The casing of the two strings will not be taken into account when the strings are compared. The syntax of the function is as given below.

$Intval = strcasecmp (string strvar1, string strvar2,
int charlen)
If $Intval contains a value <0, this means that $strvar1 is less than $strvar2; however, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The strncasecmp() Function
This function is used to perform a binary comparison of two strings for the first x number of characters. The function returns the number of similar characters and stores it in an integer variable. This function is similar to the strcasecmp function. However, in this case you can specify the maximum number of characters that should be compared from both the strings.

In case the size of the string is less than the specified number of characters, then only the number of characters in the string are used for comparison. The casing is not taken into account when the strings are compared. The syntax of the function is as given below.

$Intval = strncasecmp (string strvar1, string strvar2,
int charlen)
If $Intval contains a value <0, this means that $strvar1 is less than $strvar2; however, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The strcmp() Function
This function compares the binary values of two strings and returns an integer value indicating which string’s binary value is greater. The syntax of the function is as given below.

$Intval = strcmp (string strvar1,
string strvar2)
If $Intval contains a value <0, this means that $strvar1 is less than $strvar2. However, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The strcspn() Function
This function is used to calculate the length of a string that doesn’t match the string declared in a second string. The syntax of the function is as given below.

$Intval = strcspn (string strvar1,
string strvar2)
This function returns an integer value. In the above code, $strvar1 is compared to $strvar2, and $Intvar contains the number of characters in $strvar2 that are not there in $strvar1.

The strlen() Function
This function is used to calculate the length of the specified string. The syntax of the function is as given below.

$Intval = strlen (string strvar1)
The above code returns the length of $strvar1 and stores it in the variable $Intval.

The strnatcmp() Function
This function is used for comparing two strings based on their natural ordering. The term natural ordering means that items in a list are ordered following the same rationale that a normal human being would follow to order the items. For example, a person counting items numbered from 1 to 20 would place the number 10 after the number 9. However, a computer would analyze the same list of items and place 10 immediately after 1. The syntax of the function is as given below.

$Intval = strcmp (string strvar1,
string strvar2)
If $Intval contains a value <0, this means that $strvar1 is less than $strvar2; however, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The strnatcasecmp() Function
The strnatcasecmp() function is also similar to the strnatcmp() function. The difference is that the strnatcasecmp() function performs a case-insensitive comparison between two strings.

$Intval = strcasecmp (string strvar1,
string strvar2)

If $Intval contains a value <0, this means that $strvar1 is less than $strvar2; however, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The strncmp() Function
The function performs a binary comparison of the first x number of characters. This function is similar to strcmp(), but in the case of the strncmp() function you can also stipulate the maximum number of characters that you can use from each string while performing the comparison. The comparison is, however, case sensitive. The syntax of the function is as given below.

$Intval = strncmp (string strvar1,
string strvar2, int strlen)
If $Intval contains a value <0, this means that $strvar1 is less than $strvar2; however, if the value of $Intval is >0, then $strvar1 is more than $strvar2. In case the value is 0, this means that both the strings are equal.

The str_pad() Function
This function is used for padding a specified string with another specified string. The function accepts two parameters of the string and the number of characters that need to be padded both sides of the string. If you provide the optional parameter of the string or characters that should be used to pad, they will be used. Otherwise, default spaces are used to pad the string. You also have the option to specify the pad type. The pad type can contain any of the following options: str_pad_left, str_pad_right, or str_pad_both.

As the names suggest, you can pad the string on the left side, on the right side, or on both sides. The string is not padded in case a negative value or a value less than the size of the specified string is used. The syntax of the function is as given below.

$strval = str_pad(string strvar1, int pad_length,
[, string pad_str, int pad_type])

The strpos() Function
The function is used to search for the first time a specified string appears in another string. For example, you might want to search where a certain word appears for the first time. The function returns a numeric value of the position where the string occurs for the first time. In the example given below, $strvar2 is searched for in $strval1, and the position where the string is first displayed is sent back and stored in the variable $Intval. The syntax of the function is as given below.

$Intval = strpos (string strvar1, string strvar2 [,
int $offset])
The variable $Intval contains the value False if the string $strvar2 is not found in $strvar1; otherwise, it contains True. If $strvar2 contains an integer value, then the value is treated as the ordinal position of the character. The difference between the strpos() and strrpos() function is that in the strpos() function $strvar2 can be a string. If you specify the optional parameter $offset, the search begins after $offset number of characters in the string.

The strrchar() Function
This function is used to search for the last time a character appears in a string. The function returns the rest of the string from the point onward from where the character is found. If you don’t find the variable $strvar, the function will return the value False. However, if the string contains several characters, then only the first character will be used in the search. The syntax of the function is as given below.

$strval = strrchar(string strvar1, string strvar2)
If $strvar2 is not found, then the variable contains the value False, and if $strvar2 contains an integer value, then the value is treated as the ordinal position of the character. If $strvar2 contains an integer value, then the value is treated as the ordinal position of the character.

The strrpos() Function
This function is used to search for the last instance of a specified string that appears in another string. For example, you might want to search where a certain word appears for the last time in another string. The function returns a numeric value of the position where the string occurs for the last time. In the example given below, $strvar2 is searched for in $strval1 and the position where the string last appears is sent back and stored in the variable $Intval. The syntax of the function is as given below.

$Intval = strrpos (string strvar1,
char $searchchar)
$searchchar can only contain a single character, and even if a string is specified, only the first character of the string will be used for the search. If $strvar2 contains an integer value, then the value is treated as the ordinal position of the character.

The strspn() Function
You can use this function to find the number of characters in a string that match another specified string. The function returns an integer value. The syntax of the function is as given below.

$Intval = strspn (string strvar1,
string $strvar2)
In the code given above, the function searches for $strvar1 in the string $strvar2 and returns the part of the string $strvar1 that contains the characters.

Now that you know how to validate string information, it’s time to learn how you can validate dates entered by the user.

Validating Date Information
The date() function is used to determine if a user has entered a valid date. The function takes three integer parameters: the day, the number, and the year. If the date is valid the function returns True; otherwise, the function returns False. A month is valid if its value is between 1 and 12; the validity of the date depends on the specified month, and the year value should range between 1 and 32767. A leap year is taken into account while determining the number of valid dates in the month of February. The syntax of the function is as given below.

$strval = date(string format [, int
timestamp])

Validating Integer Information
You also have certain mathematical functions that you can use to validate the integer values entered by a user. Let’s look at a few of these functions.

The max() Function
This function is used to find the highest value from a range of values. The function returns an integer value, which is stored in a variable. The syntax of the function is given below.

$val = max (mixed var1, mixed var2,
mixed var3)
The max() function can process integer, string, float, or array variables. In the above code, if var1 is an array, the function will retrieve the highest element from the array. However, if var1 is a string, a float, or an integer, you need to pass at least two more values to determine the largest value from the range. You can specify any number of elements in the range that you want to compare. The datatype of the returned value depends on the datatypes of the passed arguments.

The min() Function
The min() function is similar to the max() function; the only difference is that in this case the lowest value from a range of values is returned. Just as in the case of the max() function, even here you can specify any number of elements in the range that you want to compare. The datatype of the returned value depends on the datatypes of the passed arguments. The syntax of the function is given below.

$val = max (mixed var1, mixed var2,
mixed var3)
In the above code, if the values passed as parameters are of the float datatype, then the function will return a float; however, if the variables are integers, then the function will return an integer value.

Functions for Validating User Input
Before you use the string, mathematical, and date functions, you need to determine the datatype of the entered information. Based on this information you can use the appropriate function. Some of these functions are given as follows.

The gettype() Function
This function can be used to retrieve the datatype of a specified variable. You can check if a variable is integer, string, boolean, double, object, array, resource, or NULL. Nowadays, instead of using this function, programmers prefer to use the functions function_exists() and method_exists(). The syntax of the function is as given below.

$strval = gettype(mixed variable)
You can use the settype() function to specify the datatype a variable should use.

The settype() Function
This function is used to specify the datatype a variable should belong to. The function accepts two parameters: the variable name and the datatype that the variable should be set to. The possible datatypes that you can use or set a variable to are integer, string, boolean, double, object, array, resource, or NULL. The syntax of the function is as given below.

$strval = settype(mixed variable,
string specified_datatype)
The is_array() Function
This function is used to determine if the specified variable is an array. The function will return the value True if the variable is an array and False if it is not an array. The syntax of the function is as given below.

$boolval = is_array(mixed variable)
The is_bool() Function
This function is used to determine if a variable contains a boolean value. The function will return the value True if the variable contains a bool value and False if it does not contain a bool value. The syntax of the function is as given below.

$boolval = is_bool(mixed variable)

The is_double() Function
This function is the same as the is_float() function and provides the same functionality.

The is_float() Function
This function is used to determine if a variable contains a float value. The function accepts a single parameter of mixed datatype and returns True if the variable contains a float value; otherwise, it returns False.

The is_int() Function
The is_int() function confirms that a variable contains an integer value. The function will return the value True if the variable contains an integer; otherwise, it will return False. The syntax of the function is as given below.

$boolval = is_int(mixed variable)
The is_integer() Function
This function is the same as the is_int() function and provides the same functionality.

The is_long() Function
This function is the same as the is_int() function and provides the same functionality.

The is_null() Function
This function determines if a variable contains a NULL value. If the variable contains a NULL value, the function will return the value True. In case the variable doesn’t contain NULL, then the function will return the value False. The syntax of the function is as given below.

$boolval = is_null(mixed variable)

The is_numeric() Function
This function is used to determine if the information entered by a user is a numeric string or an integer value. The function returns the value True if the entered information is either a numeric value or a numeric string; otherwise, it returns False.

The is_object() Function
This function is used to determine if a variable contains an object. The function returns True if the variable has an object; otherwise, it returns False. The syntax of the function is as given below.

$boolval = is_object(mixed variable)
The is_real() Function
This function is the same as the is_float() function and provides the same functionality.

The is_resource() Function
This function is used to determine if a variable is a resource. The function returns True if the variable is a resource; otherwise, it returns False. The syntax of the function is as given below.

$boolval = is_resource(mixed variable)
The is_scalar() Function
This function is used to determine whether a variable is scalar in nature. The function returns True if it is; otherwise, it returns False. You have already learned that scalar datatypes are string, integer, boolean, and float. The syntax of the function is as given below.

$boolval = is_scalar(mixed variable)

Caution Resources are not considered to belong to the scalar datatypes.

The is_string() Function
This function is used to determine if a variable contains a string value. If it does the function will return the value True; otherwise, it will return False. The syntax of the function is as given below.

$boolval = is_string(mixed variable)
The isset() Function
This function is used to determine if a variable is set or not. If the variable is set or exists, the function returns True; otherwise, False. If the variable contains the value NULL, the isset() function will still return the value False. The syntax of the function is as given below.

$boolval = isset (mixed variable)
The strval() Function
This function is used to retrieve the string value stored in a variable. The function returns the string value of the variable supplied as a parameter. The variable can be of any scalar datatype. The syntax of the function is as given below.

$strval = strval(mixed variable)
Caution You cannot use this function to evaluate or change arrays or objects.

Besides user input, other information that needs to be validated is the e-mail address.