Form Validation
When we create forms and allow users to input data, we typically need to validate and sanitize the data before storing and processing it. Form validation can be done at the client side using JavaScript and the server-side using a language like PHP. Although, form validation on the client-side is fast, effcient, and provides a better user expierence, client-side validation is not a safe and secure approach since the user can choose to turn-off JavaScript, use a browser that does not support it, or simply alter the client code from the browser’s developer tools. Thus, it is imperative to choose a more secure approach and validate input data on the server using PHP. In this lecture note, we will look at how form validation is done in JavaScript and PHP.
Form Validation on the client side
Consider the following sign up HTML form that contains three input fields: user name, email, and password. The user name must be between 8 and 32 characters and may contain a combination of letters and numbers. While email validation is nearly impossible due to the various ways an email can be valid, we can use a regular expression that is defined in RFC 5322 and works almost on most valid email addresses but is not 100% accurate. The best way to validate an email address is to send out a confirmation email to the provided address and see if the user clicks on the confirmation link or not. In this lecture note, we will use a regular expression to validate the given email address.
The password must be between 8 and 32 characters with at least one letter, one digit, and one special character.
|
|
More Form validation Options
PHP Extensions: The ctype extension
A PHP extension is a custom library or plug-in that provides a function that can be used in your PHP application. Some extenstions are turned on by default while others need to be explicitly enabled.
The character type checking ctype
extension, provides a set of functions to check whether a character or string falls into a specific character class. This extension is enabled on by default. Below is a list of ctype functions that may be used to check and validate a string:
function | description | example |
---|---|---|
ctype_digit | Check for numeric character(s) | ctype_digit("123"); |
ctype_alnum | Check for alphanumeric character(s) | ctype_alnum("1a2b3c4d"); |
ctype_alpha | Check for alphabetic character(s) | ctype_alpha("abcdefg"); |
ctype_cntrl | Check for control character(s) | ctype_cntrl("\n\r\t"); |
ctype_lower | Check for lowercase character(s) | ctype_lower("abc"); |
ctype_upper | Check for uppercase character(s) | ctype_upper("ABC"); |
ctype_punct | Check for any printable character which is not whitespace or an alphanumeric character | ctype_punct(",.?!"); |
ctype_space | Check for whitespace character(s) | ctype_space(" \t "); |
ctype_xdigit | Check for character(s) representing a hexadecimal digit | ctype_xdigit("AB10BC99"); |