PHP Form Validation

In this chapter you will learn:

  1. What is form validation
  2. CTYPE functions
  3. Example - Validation script

Description

Basic input validation in PHP is done using the following functions.

  • is_string(),
  • is_numeric(),
  • is_float(),
  • is_array(), and
  • is_object().

Each of these functions take a variable and return true if that variable is of the appropriate type.

The three basic validation checks we should do.

  • whether we have required variables,
  • whether the variables have a value assigned, and
  • whether they have the the type we are expecting.

After the basic check, we can do more check, such as integer value range, the string length, count of array elements, etc.

CTYPE functions

There are eleven CTYPE functions in total. they work in the same way as is_numeric().

Function Meaning
ctype_alnum() Matches A?Z, a?z, 0?9
ctype_alpha() Matches A?Z, a?z
ctype_cntrl() Matches ASCII control characters
ctype_digit() Matches 0?9
ctype_graph() Matches values that can be represented graphically
ctype_lower() Matches a?z
ctype_print() Matches visible characters (not whitespace)
ctype_punct() Matches all non-alphanumeric characters (not whitespace)
ctype_space() Matches whitespace (space, tab, new line, etc.)
ctype_upper() Matches A?Z
ctype_xdigit() Matches digits in hexadecimal format

<?PHP
$var = "123456789a";
print (int)ctype_digit($var);
?>

Example

The following code checks whether the $Age variable has a numeric value between 18 and 30.


if (isset($Age)) {
        if (is_numeric($Age)) {
                if (($Age > 18) && ($Age < 30)) {
                        print " input is valid";
                } else {
                        print "Sorry, you're not the right age!";
                }// j a  va 2  s. com
        } else {
                print "Age is incorrect!"
        }
} else {
        print "Please provide a value for Age.";
}

Next chapter...

What you will learn in the next chapter:

  1. What is a form file upload field
  2. Accessing Information on Uploaded Files
  3. Fields of file information
  4. Error
  5. Limiting the Size of File Uploads
  6. Storing and Using an Uploaded File
  7. Example - Handling File Uploads
  8. Example - Move a uploaded file
  9. Example - Checking Uploaded Files
  10. Example - File Upload Script and Copy
Home » PHP Tutorial » PHP Form
PHP HTML Forms
PHP GET and POST
PHP Form Elements
PHP Form TextField
PHP Form Password Field
PHP Form Textarea
PHP Form CheckBox
PHP Form Select
PHP Form RadioButton
PHP Form Submit
PHP Form Reset
PHP Form Push Button
PHP Form Image
PHP Form Hidden Field
PHP Split Form Across Pages
PHP Form Validation
PHP Form File Upload
PHP Form Demo
PHP Form Empty Fields
PHP Form Multi-Value Fields
PHP Redirect after a Form Submission