Adding Server-side Capabilities to Form Validation with the DOM - Adding server-side capabilities to the original application
(Page 3 of 5 )
In simple terms, the form validation class that I plan to develop here is really easy to grasp. It should also be familiar to you, since I’ve been using it in some of my previous PHP tutorials. If this doesn’t ring any bells to you, here is the partial signature of this new class, which has some helpful methods aimed at validating different types of data:
class FormValidator{
private $errors=array();
private $method;
const MIN=4;
const MAX=32;
public function __construct(){
$this->method=$_POST;
}
// validate empty values
public function validateEmpty($field,$errorMessage){
if(!$this->method[$field]||trim($this->method[$field])
==''||strlen($this->method[$field])<self::MIN||strlen($this->
method[$field])>self::MAX){
$this->errors[]=$errorMessage;
}
}
// validate integer values
public function validateInt($field,$errorMessage){
if(!$this->method[$field]||!is_numeric($this->
method[$field])||intval($this->method[$field])!=$this->method[$field]){
$this->errors[]=$errorMessage;
}
}
// validate numeric values
public function validateNumber($field,$errorMessage){
if(!$this->method[$field]||!is_numeric($this->method[$field])){
$this->errors[]=$errorMessage;
}
}
// validate range of values
public function validateRange($field,$errorMessage){
if(!$this->method[$field]||$this->
method[$field]<self::MIN||$this->method[$field]>self::MAX){
$this->errors[]=$errorMessage;
}
}
}
For this concrete case, the “FormValidator” class shown above presents a few simple methods which come in handy for performing strong validation on the data entered in a given web form. As you can see, the aforementioned class is capable of checking for empty strings, numeric and alphabetic values, predefined ranges of data, and so forth.
Logically, due to its extreme versatility, the previous class can be easily improved to extend its functionality even more. Considering this, in the next few lines I’ll be adding some extra methods to the referenced class so it can be used in conjunction with the DOM-based validation script that you learned in previous tutorials.
Sounds really interesting, right? So go ahead and read the following section.
Next: Completing the form validation class >>
More JavaScript Articles
More By Alejandro Gervasio