Currently, I am working on a minimal MVC framework for a somewhat ambitious project. I chose to host this website using the latest and greatest: PHP-FPM on nginx running PHP 5.3. After realizing that I needed a form validation library, I came up with one that is fairly easy to use and somewhat extensible. This is the first time I have been able to use Closures in PHP code so maybe I am just a little bit geeky-giddy.
The Code
My only real criteria when I began writing is that I wanted to use method chaining so I could “stack up” rules on a given post variable. Here is what I ended up with:
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | <?php class FormValidator { private $messages = array(); private $errors = array(); private $rules = array(); private $fields = array(); private $functions = array(); private $haspostdata = FALSE; public function __construct() { $this->haspostdata = ( $_SERVER['REQUEST_METHOD'] === 'POST' ) ? TRUE : FALSE; } /*** ADD NEW RULE FUNCTIONS BELOW THIS LINE ***/ /** * email * @param string $message * @return FormValidator */ public function email($message='') { $message = ( empty ($message) ) ? '%s is an invalid email address.' : $message; $this->set_rule(__FUNCTION__, function($email) { return ( filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE ) ? FALSE : TRUE; }, $message); return $this; } /** * required * @param string $message * @return FormValidator */ public function required($message='') { $message = ( empty ($message) ) ? '%s is required.' : $message; $this->set_rule(__FUNCTION__, function($string) { return ( empty ($string) ) ? FALSE : TRUE; }, $message); return $this; } /** * numbersonly * @param string $message * @return FormValidator */ public function numeric($message='') { $message = ( empty ($message) ) ? '%s must consist of numbers only.' : $message; $this->set_rule(__FUNCTION__, function($string) { return ( preg_match('/^[-]?[0-9.]+$/', $string) ) ? TRUE : FALSE; }, $message); return $this; } /** * * @param int $len * @param string $message * @return FormValidator */ public function minlength($minlen, $message='') { $message = ( empty ($message) ) ? '%s must be at least ' . $minlen . ' characters or longer.' : $message; $this->set_rule(__FUNCTION__, function($string) use ($minlen) { return ( strlen(trim($string)) < $minlen ) ? FALSE : TRUE; }, $message); return $this; } /** * * @param int $len * @param string $message * @return FormValidator */ public function maxlength($maxlen, $message='') { $message = ( empty ($message) ) ? '%s must be no longer than ' . $maxlen . ' characters.' : $message; $this->set_rule(__FUNCTION__, function($string) use ($maxlen) { return ( strlen(trim($string)) > $maxlen ) ? FALSE : TRUE; }, $message); return $this; } /** * * @param int $len * @param string $message * @return FormValidator */ public function length($len, $message='') { $message = ( empty ($message) ) ? '%s must be exactly ' . $len . ' characters in length.' : $message; $this->set_rule(__FUNCTION__, function($string) use ($len) { return ( strlen(trim($string)) == $len ) ? TRUE : FALSE; }, $message); return $this; } /** * * @param string $field * @param string $label * @param string $message * @return FormValidator */ public function matches($field, $label, $message='') { $message = ( empty ($message) ) ? '%s must match ' . $label . '.' : $message; $matchvalue = $this->getval($field); $this->set_rule(__FUNCTION__, function($string) use ($matchvalue) { return ( (string)$matchvalue == (string)$string ) ? TRUE : FALSE; }, $message); return $this; } /*** ADD NEW RULE FUNCTIONS ABOVE THIS LINE ***/ /** * callback * @param string $name * @param mixed $function * @param string $message * @return FormValidator */ public function callback($name, $function, $message='') { if ( is_callable($function) ) { // set rule and function $this->set_rule($name, $function, $message); } elseif ( is_string($function) && preg_match($function, 'callback') !== FALSE ) { // we can parse this as a regexp. set rule function accordingly. $this->set_rule($name, function($value) use ($function) { return ( preg_match($function, $value) ) ? TRUE : FALSE; }, $message); } else { // just set a rule function to check equality. $this->set_rule($name, function($value) use ( $function) { return ( (string)$value === (string)$function ) ? TRUE : FALSE; }, $message); } return $this; } /** * validate * @param string $key * @param string $label * @return bool */ public function validate($key, $label='') { // do not attempt to validate when no post data is present if ( $this->haspostdata ) { // set up field name for error message if ( !empty ($label) ) { $this->fields[$key] = $label; } // try each rule function foreach ($this->rules as $rule => $is_true) { if ( $is_true ) { $function = $this->functions[$rule]; if ( is_callable($function) ) { if ( $function($this->getval($key)) === FALSE ) { $this->register_error($rule, $key); // reset rules $this->rules = array(); return FALSE; } } } } // reset rules $this->rules = array(); } } /** * has_errors * @return bool */ public function has_errors() { return ( count($this->errors) > 0 ) ? TRUE : FALSE; } /** * set_error_message * @param string $rule * @param string $message */ public function set_error_message($rule, $message) { $this->messages[$rule] = $message; } /** * get_error * @param string $field * @return string */ public function get_error($field) { return $this->errors[$field]; } /** * get_all_errors * @return array */ public function get_all_errors() { return $this->errors; } /** * getval * @param string $key * @return mixed */ private function getval($key) { return ( isset ($_POST[$key]) ) ? $_POST[$key] : FALSE; } /** * register_error * @param string $rule * @param string $key */ private function register_error($rule, $key) { $message = $this->messages[$rule]; $field = $this->fields[$key]; if ( empty ($message) ) $message = '%s has an error.'; if ( empty ($field) ) $field = "Field with the name of '$key'"; $this->errors[$key] = sprintf($message, $field); } /** * set_rule * @param string $rule * @param closure $function * @param string $message */ private function set_rule($rule, $function, $message='') { // do not attempt to validate when no post data is present if ( $this->haspostdata ) { if ( ! array_key_exists($rule, $this->rules) ) { $this->rules[$rule] = TRUE; if ( ! array_key_exists($rule, $this->functions) && is_callable($function) ) { $this->functions[$rule] = $function; } if ( !empty ($message) ) { $this->messages[$rule] = $message; } } } } } ?> |
Please note: This only works for forms submitted with POST. However, it can be easily modified to work with GET also.
Usage
Now, let’s say that I have a form and I want to validate an email field and set up a password. The password must be at least 10 characters and the password confirmation field must match the password field. On top of that, I have a simple captcha where I just ask the user to add two integers that equal 10. With my class, I only need to write the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $formval = new FormValidator(); $formval->required()->email()->validate('email', 'Email Address'); $formval->required()->minlength(10)->validate('password', 'Password'); $formval->required()->matches('password', 'Password')->validate('password2', 'Password Confirmation'); $formval->required()->callback('captcha', function($value) { return ( preg_match('/^\d\s*\+\s*\d$/', trim($value)) && eval ($value) == 10 ) ? TRUE: FALSE; }, '%s does not add up to 10!')->validate('captcha', 'Captcha'); if ( $formval->has_errors() ) { print_r($formval->get_all_errors()); } else { // submit the form! } |
Pretty simple!
I have not started using this class heavily ( I just finished it) so let’s call it alpha code for now.
0