Simple web form validation in PHP

PHP Validation
A few you of may know that I’m a currently enrolled in Web development program at Humber. Last week we were assigned a task to make a simple web form validation in PHP in OOP style,So we had to make use of couple of classes. I tried to made validation classes as generic and as straight forward as possible. In this sample of code ,there are 4 classes for required fields, Regular expression, Range and length. I’ll explain briefly all of them, please keep in mind this code is only for educational purpose and not meant to be used in production environment.

Required fields

Starting with our first class is required which has only function valid that takes a variable as an parameter and return false if empty and true in else case.For checking the value of variable i could have used  empty() function but this function return true if variable has 0 value and in few other cases. You may head up to and read more about this function. I ended simply comparing $var with empty quotes, which served my purpose quite gracefully.


My second class deals with checking length of values in fields. Initially I started fondling with string length function of PHP but then I took the simple approach and used regular expression to check for minimum length. length class has 1 function lengthCheck and it takes 2 parameters a value and a second one for length.


For pattern matching I made a class pattern with number of functions.alphaOnly and numericOnly are generic function that can be used in conjunction with required and length according to logic required. Others email,phone url can be used as their name suggest.Apart from this I created a custom function which accepts Regex pattern and value to be compared for validating any customs values in form.


Initially I intended to make check range in 1 function but then I kept it simple and divided the logic in three parts.


Here is code snippet of form I used to test all these validation classes.I create objectects of all classes and called their respective member function and validated my form.There are many ways this code can be improved, if you have any suggestion feel free to leave it in the comments.