OOP validation PHP -
currently i'm trying validate email address via oop php arrays can add additional functions later, when insert valid email address validation still fails, think perhaps arrays set wrong i'm not entirely sure, additionally had tried different different operators check if email function output different results mentioned seems fail, advice appreciated
class login { private $email, $password, $database, $db = null; public function __construct() { $this->db = new database; } public function validemail($email) { return (filter_var($email, filter_validate_email) !== false); } } <?php require "classes/login.class.php"; $validate = new login(); require "loadclasses.php"; if ($_server['request_method'] == 'post') { $email = $pass = ""; $post = filter_input_array(input_post, filter_sanitize_string); $email = $post['email-login']; $pass = $post['password-login']; $errors = array(); $fields = array( 'email-login' => array( 'validate' => 'validemail', 'message' => 'enter valid email address' ) ); foreach($fields $key => $value) { if(isset($fields[$key])) { $errors[] = ['name' => $key, 'error' => $fields[$key]['message']]; } } if(empty($errors)) { $success = ['response' => 'true']; session_start(); } } header('content-type: application/json'); if (empty($errors)) { echo json_encode($success); } else { echo json_encode(["errors" => $errors]); }
as mentioned in comments - don't use functions login class.
so, how current code works:
$fields = array( 'email-login' => array( 'validate' => 'validemail', 'message' => 'enter valid email address' ) ); foreach($fields $key => $value) { // isset($fields[$key]) true if(isset($fields[$key])) { $errors[] = ['name' => $key, 'error' => $fields[$key]['message']]; } } what should like:
$fields = array( 'email-login' => array( 'validate' => 'validemail', 'message' => 'enter valid email address' ) ); // instantiate object of login class $login = new login(); foreach($fields $key => $value) { // call function `$value['validate']` (it `validemail`) $validation_result = $login->{$value['validate']}($email); // if validation fails - add error message if(!$validation_result) { $errors[] = ['name' => $key, 'error' => $value['message']]; } } and btw $post wrong variable name, suppose $_post.
Comments
Post a Comment