0

Since recently I am building web application in PHP. In purpose of learning I am building it from scratch (without using a framework).

I have a question regarding form validation (registration and login form to be specific).

Is it OK to use jQuery to validate form fields (e.g. check if all fields are full, check if email is correctly written,...) and then, if everything is right, submit form to my controller?

class RegistrationController extends Controller {

    public function __construct($data = array()) {
        userService = new UserService();
        parent::__construct($data);
    }

    public function index() {
        // form fields are correctly filled in

        if($_SERVER['REQUEST_METHOD'] == 'POST') {
            $firstName = $_POST['reg-form-first-name'];
            $lastName = $_POST['reg-form-last-name'];
            $email = $_POST['reg-form-email'];
            $password = $_POST['reg-form-password'];

            userService->createNewUser($firstName,...);
        }
    }
}

Or should I validate form inside my model in PHP? If that is the right way, can you please explain how should I print out error messages beneath the form fields if something went wrong?

What is the best practice in this situation? What provides best UX?

tereško
  • 58,060
  • 25
  • 98
  • 150
NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • You could use a FormModel for validating the form and then pass the validated data down to your Model (userService). Regarding the errors you could return an array of errors - one for each field that fails validation. – Andreas Apr 09 '17 at 16:29
  • @Andreas Can you post some example regarding this? Is this the common practice in PHP MVC? – NutCracker Apr 09 '17 at 16:43
  • 1
    To answer your question: yes. Try to move your validation logic in a Model or FormModel thus keeping your controllers thin/skinny. See a question about skinny controllers and fat models http://stackoverflow.com/q/3109715 – Andreas Apr 09 '17 at 16:54

1 Answers1

1

I would suggest moving the validation logic to your model or formModel thus keeping your controller thin/skinny.

Example:

A generic form model

abstract class FormModel 
{ 

protected $_errors = array();

//add an error for an attribute if the validation fails
public function addError($attribute, $error) { 
  $this->_errors[$attribute] = $error;
}

//get the error for an attribute
public function getError($attribute) { 
  return (isset($this->_errors[$attribute])) ? $this->_errors[$attribute] : '';
}
//get all errors for all attributes
public function getErrors() {
     return $this->_errors;       
 }

public abstract function load($data);
public abstract function validate();

}

Now for your user formModel you could to do something like:

class UserFormModel extends FormModel 
{
   public $firstName;
   public $lastName;
   public $email;
   public $password;

   public function load($data) {
      //you could use the filter_var function to read the values form the $data array. this is just an example
      $this->firstName = $data['reg-form-first-name'];
      $this->lastName = $data['reg-form-last-name'];
      $this->email = $data['reg-form-email'];
      $this->password = $data['reg-form-password'];
   }

   //this is where your form validation logic goes
   //return true if all fields are valid or false if a validation fails
   public function validate() {

       //for example
       if(empty($this->firstName)) { 
         $this->addError('firstName', 'Your first name is required');
         return false;
       }
       return true;
   }
}

Now in your controller you could do something like:

class RegistrationController extends Controller {

public function __construct($data = array()) {
    parent::__construct($data);
}

public function index() {
    // form fields are correctly filled in

    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        $formModel = new UserFormModel();
        $formModel->load($_POST); 
        if($formModel->validate()) { 
         userService = new UserService();
         userService->createNewUser($formModel->firstName,...);
        } else {
           //example
           var_dump($formModel->getErrors());
        }
    }
}
}
Andreas
  • 5,305
  • 4
  • 41
  • 60
  • Just another question @Andreas. Should there be any form validation on client side (like checking if password is equal to confirm password field, or email expression validation) when building PHP MVC? Thanks. – NutCracker Apr 10 '17 at 20:08
  • Yes, you would avoid sending the data to the server if it is not valid. But the validations on the server must exist. – Andreas Apr 11 '17 at 07:06