I have created a method that validates inputs based on a set of rules. If an error is found, it is put into an array which can later on be used to display the errors to the user.
Below is my code:
register.php
<?php
require_once('core/init.php');
if(input::inputExists()){
$validate = new validate();
$validate->checkInput($_POST, array(
'username' => array(
'formatted_name' => 'username',
'required' => 'true',
'min' => 4,
'max' => 25,
'unique' => 'users'
),
'password' => array(
'formatted_name' => 'password',
'required' => 'true',
'min' => 5
),
'confirm_password' => array(
'formatted_name' => 'password confirmation',
'matches' => 'password',
'required' => 'true'
)
));
if ($validate->validationPassed()) {
// Register new member...
} else {
// Return Errors....
print_r($validate->getErrors());
}
}
?>
<form method="POST" autocomplete="off">
<div class="form-group">
<label for="username">
Username
</label>
<input type="text" name="username" id="username" />
</div>
<div class="form-group">
<label for="password">
Password
</label>
<input type="password" name="password" id="password" />
</div>
<div class="form-group">
<label for="confirm_password">
Confirm Password
</label>
<input type="password" name="confirm_password" id="confirm_password" />
</div>
<div class="form-group">
<input type="submit" />
</div>
</form>
validate.class.php
<?php
class validate {
private $errors;
private $passed = 'false';
// public function __construct(){}
public function checkInput($data, $items = array()) {
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){
if ($rule != 'formatted_name'){
if ($rule === 'required' && empty($data[$item])){
$this->addError("{$rules['formatted_name']} is required.");
}
if ($rule === 'min' && strlen($data[$item]) < $rule_value){
$this->addError("{$rules['formatted_name']} must be at least {$rule_value} characters long.");
}
if ($rule === 'max' && strlen($data[$item]) > $rule_value){
$this->addError("{$rules['formatted_name']} can be a maximum of {$rule_value} characters long.");
}
if ($rule === 'matches' && $data[$item] != $rule_value){
$this->addError("{$rules['formatted_name']} does not match {$items[$rule_value]['formatted_name']}");
}
}
}
}
}
private function addError($error){
$this->errors[] = $error;
}
public function validationPassed(){
return empty($this->errors);
}
public function getErrors(){
return $this->errors;
}
}
Any improvements, suggestions or advice you can give me?