Validation with PHP – Part 2 – The Core

The previous post “Validation with PHP – Introduction” merely scratched the surface of what can be done in regards of validating data with PHP. In this part I will be creating a basic validation class that will include a more customizable version of what we seen in the previous post and extend it with another function.

Going back to our first example, we had a form that contained a text field in which the user had to specify his/her year of birth. The rules we used for validating that data were two: make sure that the data is numeric with the is_numeric() function and that it was between 1950 and 1985 with simple operators.

Today, our form has two new fields. One that asks for the users favourite colour and another one that asks for a telephone number without spaces or any other character. To validate those three fields we could create two other functions so we end up with one function that validates each particular case or we can elaborate the function we built on the previous post so that it can validate both the year of birth and the telephone number. As for the favourite colour, we will write another one.

Let me show you what I mean by elaborate the actual function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
function validateNumeric($int_field,$int_max = FALSE,$int_min = FALSE,){
  if(is_numeric($int_field)){
    if(!empty($int_min) && $int_field <= $int_min) return FALSE;
    if(!empty($int_max) && $int_field >= $int_max) return FALSE;
   
    return TRUE;
  }
  return FALSE;
}

$int_year  = 1980;
$int_phone = 622671864;

if(validateNumeric($int_year,1985,1950)) echo "The year is valid";
if(validateNumeric($int_phone))      echo "The phone is valid";
?>

The extended function allows you to specify a minimum and/or a maximum number as a validation rule. Note that when validating the $int_year variable we specify the maximum year as the first argument and the minimum year as the second argument but when validating the phone number we just ask the function to verify if it’s a number or not. I like to put the maximum value as the second argument, right before the minimum because I find it more often situations where you don’t really care about the minimum but you do about the maximum, this is strictly something personal so feel free to change the order if you believe it’s better for your particular case.

This is ok if we just had one type of validation rules, in this case numeric values within a given range but, as I mentioned at the beginning of the post, we also want to know the users favourite colour. Since validating a colour is a completely different matter and there are hundreds of different colours out there, all we are going to do is make sure that whatever the user enters contains only letters and maybe white-spaces for the possibility of something like “pale green” as an input. Once again we will be assuming that we already have the users input in variables called “$type_field“.

1
2
3
4
5
6
7
8
9
10
11
<?php
function validateAlphaStr($str_field, $int_max = 25, $int_min = 1,){
  $regex_alpha = "/^[a-zA-Z ]{".$int_min.",".$int_max."}$/";
  if (preg_match($regex_alpha, $str_field, $arr_matches))   return TRUE;
  return FALSE;
}

$str_field = "red";

if(validateAlphaStr($str_field)) echo "The colour is valid";
?>

Lets explain the code a little bit. We created another function called validateAlphaStr that takes three arguments. The first one is the data we want to validate, the second and third ones are the minimum and maximum number of characters for that data. Those two arguments are not mandatory and have default values just like on the previous function. That means that if we don’t specify them it will use those default values instead.

The validation is done through a regular expression using the preg_match function. In common words the regular expression reads:
This will match if the only thing on $str_field is a string made with lowercase and uppercase letters and white-spaces with a length ranging between $int_min and $int_max, all matches will be stored on an array called $arr_matches“.

This means that if we try to validate “pink” it will work but if we try to validate “colour name longer than twentyfive characters” or “red 2” it will fail. Note that we could make the very long colour name succeed if we specify the maximum length to a higher number.

Last thing we need to do is to place those functions inside a class so they can share private functions for common validations like length and duplicates.
And this is where the magic happens, we will be transitioning from individual calls to a validation function to multiple calls from a validation class, lets do this!
That means that in one single call we will be able to validate against multiple rules:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
class validate{
  public function startValidate($field,$str_validate_rules){
  $this->int_errors = 0;
 
    if(strpos($str_validate_rules,',') == false){
      $arr_rules[0] = $str_validate_rules;
    }else{
      $arr_rules = explode(',',$str_validate_rules);
    }
   
    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++;
      }
    }
   
  if($this->error_count > 0) return false;
  return true;
  }

  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->startValidate("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!
*/

?>

Don’t worry, I will explain this line by line on the next post.

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.