Validation doesn’t necessarily mean just form validation. We can also validate any variable, in fact any data against a set of rules. Whether the data passes or not those rules is what makes it valid or invalid. I will be making a series of posts explaining specific validation rules and extending those with multiple examples.
In the end, we will have a full featured form validation system with error messages, customization and a lot more features.
Today I will show you a very basic introduction to validation.
Lets say I have a form with only one field which asks the user his/her year of birth. To validate the user input we will run a function that will return TRUE if it’s valid and FALSE if it’s not valid. That will be it. We will be assuming that we already have the user input stored in a variable named $int_year.
1 2 3 4 5 6 7 8 9 10 11 | <?php function validateYear($int_year){ if(is_numeric($int_year)){ return TRUE; } return FALSE; } $int_year = 1987; if(validateYear($int_year)) echo "It's valid"; ?> |
This will validate as correct and therefore output the success message since 1987 is a number.
Okay, I admit it. This example is overly simplified and does not need a custom function since is_numeric already provides the functionality we were after but you grasp the concept, so lets make it a little bit harder. Lets imagine that we only want to consider valid inputs, those who are between 1950 and 1985. The previous example will look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php function validateYear($int_year){ if(is_numeric($int_year)){ if($int_year > 1950 && $int_year < 1985){ return TRUE; } } return FALSE; } $int_year = 1987; if(validateYear($int_year)) echo "It's valid"; ?> |
This example will not validate as correct and therefore will not output the success message because, even though 1987 is a number (first condition), 1987 is not between 1950 and 1985 (second condition). If we changed the value of $int_year to 1980 for example, it will be perfectly valid.
No posts at the moment. Check back again later!