-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate.php
74 lines (60 loc) · 1.56 KB
/
Validate.php
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
<?php
class Validate
{
private $passed = false, $errors = [], $db = null;
public function __construct() {
$this->db = Database::getInstance();
}
public function check($source, $items = []) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = $source[$item];
if($rule == 'required' && empty($value)) {
$this->addError(ucfirst($item) . " is required");
} else if(!empty($value)) {
switch ($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError(ucfirst($item) . " must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError(ucfirst($item) . " must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->db->get($rule_value, [$item, '=', $value]);
if($check->count()) {
$this->addError("{$item} already exists.");
}
break;
case 'email':
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError("{$item} is not an email");
}
break;
}
}
}
}
if(empty($this->errors)) {
$this->passed = true;
}
return $this;
}
public function addError($error) {
$this->errors[] = $error;
}
public function errors() {
return $this->errors;
}
public function passed() {
return $this->passed;
}
}