title: What is the cleanest way to handle validation errors with PHP?
body: <p>I have looked for better ways to handle validation for as long as I've been developing web applications. Catching multiple validation errors is frequently necessary, so I wanted to know if there was a better way to do it than the following.</p>
  
  <p>Right now I have an <code>assert</code> method in a framework I've developed myself. An example of the method is this:</p>
  
  <p><code>assert(($foo == 1), 'Foo is not equal to 1');</code></p>
  
  <p>If the condition in the first argument is false, the error message in the second argument is added to an <code>$errors</code> array (which is wrapped in a class (referenced by <code>$eh</code> below) that provides convenience functions such as <code>hasErrors()</code>).</p>
  
  <p>This method works but is messy in practice. Consider this code:</p>
  
  <pre><code>public function submit($foo, $bar, $baz)
  {
      assert(($foo == 1), 'Foo is not equal to 1');
      assert(($bar == 2), 'Bar is not equal to 2');
  
      if (!$eh-&gt;hasErrors())
      {
          assert(($baz == 3), 'Baz is not equal to 3');
  
          if (!$eh-&gt;hasErrors())
          {
              finallyDoSomething();
              return;
          }
      }
  
      outputErrors();
  }
  </code></pre>
  
  <p>This is something fairly common. I want to check two conditions before moving on, and then if those pass, check a third condition before finally doing what I want to do. As you can see, most of the lines in this code are related to validation. In a real application, there will be more validation and possibly more nested if statements.</p>
  
  <p>Does anyone have a better structure for handling validation than this? If there are frameworks that handle this more elegantly, what are they and how do they accomplish it? Multiple nested if statements seem like such a 'brute-force' solution to the problem.</p>
  
  <p>Just a note, I understand it would probably be a good idea to wrap some common validation functions in a class so that I can check length, string format, etc., by calling those functions. What I am asking is a cleaner approach to the code structure, not how I am actually checking the errors.</p>
  
  <p>Thank you!</p>