Where to validate users input?

Viewed 633

I am developing a new application using object oriented approach with some REST involved, I am not using any frameworks.

The question I have is where is the best place to validate a user’s input in a setter like below:

public function setSalary($salary)
{
    if (Validator::money($salary))
        $this->salary = $salary;
    else
        return 'Error that is an invalid number';
}

Or in the controller?

public function updateSalary()
{
    $errors = array();

    if (Validator::money($_POST['salary']))
        $salary = $_POST['salary'];
        else
            $errors ['salary']  = 'Error that is an invalid number';

    if(count($errors))
        return $errors;

    $employee = new Employee($_POST['e_Id']);
    $employee->setSalary($salary);

    $employee->save();
}

If I was to put in the setter how should my controller look, and return validation errors?

I have seen most people do validation in the controller, however I think should be the models responsibility for validation as it going to be using the data, and we can reuse that model without repeating ourselves. However there can be times when validation rules may need to be different in some special cases like different validation for a different view or different validation for a supper admin.

Which one would you say is in accordance with best practices?

5 Answers
Related