title: MVC - User input validation: controller, model or both
body: <p>I know questions like this one have been asked various times on stackoverflow, but even after having read those, I remain confused. I would like to gain clarity as to where form validation is supposed to be handled through demonstrating an issue with an example.</p>
  
  <p>Let's say I have a form on my website, with a field that somebody fills out and subsequently submits. The model would like the controller to pass it this value correctly in order to process that value internally. The model receives the input through the function <code>getInput</code>, which sets the following rules:</p>
  
  <ul>
  <li>The input must be of the string type.</li>
  <li>The input must be of more than 0 and fewer than or equal to 100 characters.</li>
  <li>The input must match the pattern of an e-mail address.</li>
  </ul>
  
  <p>I suppose I should throw an exception inside <code>getInput</code>, if any of these conditions do not meet; after all, the controller passed a value that did not match the rules that had been set by the model.</p>
  
  <p>Apart from the aforementioned rules, the controller (at least I am rather certain this applies to the controller) must also validate whether the input value had been set in the first place, before the script proceeds with the other three rules.</p>
  
  <p>Now my question is: which of these (4) rules are to be validated by the controller, and which ones by the model? It is apparent that the controller knows what the model requests, so that it can adjust to that (and if it doesn't, it may face the consequence of an exception being thrown). On the other hand, it seems redundant to have several controllers, which all make use of the model and its <code>getInput</code>, validating the same kind of string so that it matches the rules set by the model. Also, if the controller firstly validates if the input is of the correct length - for example - and the model does the precise same thing immediatly after that, once <code>getInput</code> gets called, even more redundancy seems to arise.</p>
  
  <p>In the example, the controllers and the model could be seen as a partnership with the model being a grumpy perfectionist, who is going to validate the input he gets from the controllers, regardless of the actions of these cordial partners who try hard to supply him with all his desires. But isn't such a relation terribly inefficient?</p>