Last active
August 18, 2022 05:09
-
-
Save rickd-uk/59594a20ca76fecdf2f037c7cf6e06bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Model extends Database | |
{ | |
protected function validate_empty($data, $field, $err_message = null) | |
{ | |
if (empty($data[$field])) { | |
// Use first part of field name in string e.g. currency_id required => currency required | |
if (empty($err_message)) { | |
$err_message = explode("_", $field)[0] . ' required'; | |
} | |
$this->errors[$field] = $err_message; | |
return true; | |
} | |
return false; | |
} | |
protected function validate_text($data, $field, $regex, $err_msg) | |
{ | |
if (!preg_match($regex, trim($data[$field]))) { | |
$this->errors[$field] = $err_msg; | |
} | |
} | |
} | |
class Course_model extends Model | |
{ | |
public function validate($data) | |
{ | |
$this->errors = []; | |
$this->validate_empty($data, 'title', 'Enter course title') | |
|| $this->validate_text($data, 'title', "/^[a-zA-Z_ ]+$/", "Course titles can only have letters, spaces and '_'"); | |
$this->validate_empty($data, 'primary_subject', "Enter a primary subject") | |
|| $this->validate_text($data, 'title', "/^[a-zA-Z_ ]+$/", "Primary subjects can only have letters, spaces and '_'"); | |
if (empty($this->errors)) { | |
return true; | |
} | |
return false; | |
} | |
} | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just created some validation functions that were more generic and put them in the Model class, so they can be used by any model. In my opinion, the text validation can be made more generic by grouping common validations. Many of them will be probably be similar.
What do you think?