Form and Spelling Validation -
(Page 3 of 14 )
The first validation functions we will cover will do some very basic checks for us. We will validate if a variable contains only digits, only letters, and if it conforms to a certain length. These basic validation functions are useful on their own and as helper functions in other validation routines.
Checking for Digits Only The first function we will look at determines if the string passed to it contains only numbers. We accomplish this by using a regular expression that encompasses the negating operator. If any character within the variable is a not a number, this function will return FALSE.
<?php function isDigits($element) { return !preg_match ("/[^0-9]/", $element); } ?> |
Checking for Letters Only The next function we will examine is almost identical to the isDigits() function. This one, however, will verify if a string contains only letters. Like the isDigits() function, we use a regular expression with the negating operator to determine if any character in the string does not match the pattern we specify. If any character within the variable is not a letter, isLetters() will return FALSE.
<?php function isLetters($element) { return !preg_match ("/[^A-z]/", $element); } ?> |
Checking a String for Length Now, let's look at a function that will check the length of a string and return FALSE if the length is not within a range we specify. For this task, we will make use of the strlen() function to determine the length of the string and then compare it to the specified minimum and maximum length.
<?php function checkLength($string, $min, $max) { $length = strlen ($string); if (($length < $min) || ($length > $max)) { return FALSE; } else { return TRUE; } } ?> |
Next: >>
More Miscellaneous Articles
More By Matt Wade