/mvc/components/validator
[return to app]1
<?php
2 /**
3 * Validates user-entered data
4 */
5 class validatorComponent {
6 /**
7 * Verifies a hex color (used in HTML/CSS) contains exactly six base-16 digits
8 *
9 * @param string $data
10 * @return boolean
11 */
12 public function isValidHexColor($data) {
13 return (bool) preg_match('/[0-9ABCDEF]{6}/', $data);
14 }
15
16 /**
17 * Verifies a URL is valid
18 *
19 * @param string $data
20 * @return boolean
21 */
22 public function isValidURL($data) {
23 return (bool) preg_match('#(https?|ftp)://(www\.)?(\S+\.)+[^\.\s]{1,5}(:\d+)?([\\/]\S+)*?$#i', $data);
24 }
25
26 /**
27 * Verifies an email is valid
28 *
29 * @param string $data
30 * @return boolean
31 */
32 public function isValidEmail($data) {
33 $datalen = strlen($data);
34 return ($datalen > 5 && $datalen <= 60 && preg_match('/([\w!#$%"*+\/=?`{}|~^-]+)@(([\w-]+\.)+[\w-]{2,})/',
$data));
35 }
36
37 /**
38 * Verifies password is or is not valid
39 *
40 * @param string $pass
41 * @return mixed A string containing an error message (casts to bool-true) indicates an invalid pass
42 * Bool-false indicates a valid password
43 */
44 public function isInvalidPassword($pass) {
45 $passlen = strlen($pass);
46 if ($passlen < 6) {
47 $error = 'Password is too short';
48 }
49 if ($passlen > 16) {
50 $error = 'Password is too long';
51 }
52 if (strpos($pass, ' ') !== false) {
53 $error = 'Passwords cannot contain spaces';
54 }
55 if (!isset($error)) {
56 $passwithoutnumbers = str_replace(range(0,9), '', $pass);
57 if ($passwithoutnumbers == $pass || $passwithoutnumbers == '') {
58 $error = 'Passwords must contain a mix of numbers and letters';
59 }
60 }
61 return (isset($error) ? $error : false);
62 }
63
64 /**
65 * Verifies telephone numbers
66 *
67 * @param mixed $data Phone number in numberic-format - alpha-chars like (443)300-VORK will be ignored (& then
fail)
68 * @param string $country Country code, currently US is the only validated number, other countries are only
checked
69 * for having a minimal number of numeric characters
70 * @return boolean
71 */
72 public function isValidTelephone($data, $country = 'US') {
73 if ($country == 'US') {
74 $return = (bool) preg_match('/\b([2-9]\d{2})[.\s -]?(([2-9]\d{2})[.\s -]?(\d{4}))\b/', $data);
75 if ($return && substr($data, 3, 3) == '555') {
76 $return = false;
77 }
78 } else {
79 $return = (strlen(get::component('filter')->getNumbersOnly($data)) > 6);
80 }
81 return $return;
82 }
83 }