-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_validator.php
60 lines (43 loc) · 1.21 KB
/
user_validator.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
<?php
class UserValidator {
private $data;
private $errors = [];
private static $fields = ['username', 'email'];
public function __construct($post_data){
$this->data = $post_data;
}
public function validateForm(){
foreach(self::$fields as $field){
if(!array_key_exists($field, $this->data)){
trigger_error("'$field' is not present in the data");
return;
}
}
$this->validateUsername();
$this->validateEmail();
return $this->errors;
}
private function validateUsername(){
$val = trim($this->data['username']);
if(empty($val)){
$this->addError('username', 'username cannot be empty');
} else {
if(!preg_match('/^[a-zA-Z0-9]{6,12}$/', $val)){
$this->addError('username','username must be 6-12 chars & alphanumeric');
}
}
}
private function validateEmail(){
$val = trim($this->data['email']);
if(empty($val)){
$this->addError('email', 'email cannot be empty');
} else {
if(!filter_var($val, FILTER_VALIDATE_EMAIL)){
$this->addError('email', 'email must be a valid email address');
}
}
}
private function addError($key, $val){
$this->errors[$key] = $val;
}
}