Validation with PHP – Part 3 – Explaining the class

1
2
3
4
<?php
class validate{
  public function fieldValidate($field,$str_validate_rules){
  $this->int_errors = 0;

On these three lines we declare a new class called validate. It has a public function called fieldValidate that takes two attributes. The first one is the variable that contains the field data we want to validate and the second one is a string containing the rules we want to use for the validation. This function is in charge of calling the appropriate private functions that will do the actual validation. We provide a string, and this function extracts and processes the rules.

$this->int_errors is a variable that will contain the number of errors after the validation process is done. In future posts we will add custom error messages, for now, it’s just a binary situation. It either validates or it doesn’t, we don’t know which rule failed.

1
2
3
4
5
    if(strpos($str_validate_rules,',') == false){
      $arr_rules[0] = $str_validate_rules;
    }else{
      $arr_rules = explode(',',$str_validate_rules);
    }

These lines ensure that even if we provide only one rule, it will be stored on an array so the next part of the code works. It may be doable in a more efficient way, but mind that I’m coding this on the fly just to help you understand this. If there is more than one rule, they will be separated by commas, so what we do is store them in an array by using the explode function.

1
2
3
4
5
6
7
8
9
10
    foreach($arr_rules as $str_rule){
      if($str_rule == "required") if(!$this->checkEmpty($field))      $this->int_errors++;
      if($str_rule == "numeric")  if(!$this->checkIsNumeric($field))  $this->int_errors++;
      if($str_rule == "alpha")    if(!$this->checkIsAlpha($field))    $this->int_errors++;
      if(strpos($str_rule,"length") === 0){
        $int_min = substr($str_rule,7,strpos($str_rule,"to")-7);
        $int_max = substr($str_rule,strpos($str_rule,"to")+2,-1);
        if(!$this->checkLength($field,$int_max,$int_min))         $this->int_errors++;
      }
    }

This part of the code is very important. It’s a loop that will decide which functions to call and for each particular function which attributes to use. The format I’m using for setting multiple validation rules as the second attribute when calling the fieldValidate function is the following:

  • “validationRule” For rules with no arguments
  • “validationRule{argument}” For rules with one argument
  • “validationRule{argument_onetoargument_two}” For rules with two arguments

Once again, multiple validation rules will be separated by commas. The first three rules, (required, numeric and alpha) require no arguments and therefore can be declared on a single line. Those read something like this: “If the value of variable $str_rule is equal to this keyword then if it doesn’t pass the rule linked to this keyword increase the value of $this->int_errors by one.” On the other hand, the “length check requires two attributes so we need to extract them before we can call the checkLength function. To do so, we use the function substr to locate the keyword ‘to’ that works as a separator between those two arguments. If the function doesn’t return true, we increase the value of the error count on $int_errors.

1
2
3
  if($this->int_errors > 0) return false;
  return true;
  }

This basically means “If there the error count stored in $int_errors is higher than zero, return false!” otherwise, return true.
The following code consists in all the private functions that are available for the public fieldValidate function to call. Each of those private functions will return true or false depending on whether the data is correct or not. Those are self-explanatory but if you have any doubts feel free to comment asking about it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  private function checkEmpty($field = null){
    if(!$field) return false;
  return true;  
  }
 
  private function checkLength($field,$int_max = 99,$int_min = 1){
    if(strlen($field) < $int_min || strlen($field) > $int_max) return false;
  return true;  
  }
 
  private function checkNumericValue($int_field,$int_max,$int_min){
    if($int_field < $int_min || $int_field > $int_max) return false;
  return true;  
  }
 
  private function checkIsNumeric($int_field){
    if(!is_numeric($int_field)) return false;
  return true;
  }
 
  private function checkIsAlpha($str_field){
    if(!preg_match("/^[a-zA-Z ]{1,}$/", $str_field)) return false;
  return true;  
  }
}

$validate = new validate;
if($validate->fieldValidate("test","required,length{2to6},alpha")) echo "valid field";
echo $validate->int_errors;

/*
The output of this will be "Valid field - 0" since "test" doesn't break any rules.
$int_errors is still 0 since we didn't break the rules!
*/

?>

Now, using this class we can validate a single field against multiple rules. On the next part of this series we will go on and introduce an error output system that will allow us to locate the point where the validation failed and show us a message explaining what happened. Then on further parts we will introduce the ability to choose the language of the messages and move those to a separate file that will something like a language file.

Stay tuned.

About Juan

Hola! Me llamo Juan y soy un programador de 23 años de Madrid. Este es mi blog personal dedicado a la programación en general aunque con cierta predilección hacia PHP y Java.