Form Validation with Progressive Enhancement: Final Touches
In this sixth part of a series, I finish building a sample web application tasked with validating web forms via Ajax and PHP. The use of Progressive Enhancement is crucial to keeping the application working as expected, even if JavaScript is disabled on the browser.
Form Validation with Progressive Enhancement: Final Touches - A basic data validation PHP class (Page 3 of 4 )
As stated in the preceding segment, in this case the component tasked with validating the data entered in the previous web form will be a simple PHP class not surprisingly called “Validator” (yes, sometimes my creativity with names is really amazing). The underlying logic of this class is very simple to follow. Its corresponding definition looks like this:
(Validator.php)
<?php
class Validator
{
protected $_errors = array();
protected $_errorPrefix = '<p>';
protected $_errorSufix = '</p>';
// check an empty string
public function checkEmpty($value)
{
$value = $this->sanitizeValue($value);
if ($value === '')
{
$this->_errors[] = 'The entered value must be a non-empty string.';
}
return $this;
}
// check an integer number
public function checkInteger($value, array $options = array())
{
$value = $this->sanitizeValue($value);
if (!filter_var($value, FILTER_VALIDATE_INT, $options))
{
$this->_errors[] = 'The value ' . $value . ' must be an integer number.';
}
return $this;
}
// check a float number
public function checkFloat($value, array $options = array())
{
$value = $this->sanitizeValue($value);
if (!filter_var($value, FILTER_VALIDATE_FLOAT, $options))
{
$this->_errors[] = 'The value '. $value . ' must be a float number.';
}
return $this;
}
// check an email address
public function checkEmail($value)
{
$value = $this->sanitizeValue($value);
if (!filter_var($value, FILTER_VALIDATE_EMAIL))
{
$this->_errors[] = 'The value '. $value . ' must be a valid email address.';
As you can see above, the “Validator” class implements a few discrete methods for checking some typical data types, such as integer and float numbers, empty strings and email addresses. As one might expect, each error that occurs during the validation process is stored on the protected $_errors property, which is used internally by the “validate()” method to determine whether or not the supplied data is correct.
Due to the flexible nature of the class, it’s really easy to extend its current capabilities via additional methods. For demonstration purposes, however, its existing functionality is more than acceptable, so implementing those extra methods will be left as homework for you.
So far, so good. Having defined a class that’s capable of checking some basic data types, we'll now create a script that consumes its API, thus getting the previous form validation program up and running.
This final script will be created in the following section. To get there simply click on the links that appears below and keep reading.