SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot Overunner's Avatar
    Join Date
    Mar 2004
    Location
    Sweden
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Questions about form validation and MVC

    Hi

    This is just my thoughts about validating a form using a MVC-pattern. Though I have some questions: First of all, the validation should take place in the Controller, right? Since I choose an action based on what the result of the validator is.

    Code example:
    PHP Code:
      class UserRegistrationController extends Controller
      
    {
        function &
    getAction()
        {
          
    $validator = new Validator();
          
    $validator->addRule(new RequiredRule('Username''The Username field is required!'));
          
    $validator->addRule(new MatchRule('Password''ConfirmPassword''The password was not confirmed!');
          
    // Some more rules...

          
    if ($validator->isValid())
          {
            return new 
    SuccessfullRegistrationAction();
          }
          else
          {
            return new 
    UnSuccessfullRegistrationAction($validator->getErrorList());
          }
        }
      } 
    PHP Code:
      class SuccessfullRegistrationAction extends Action
      
    {
        function 
    execute() { }

        function &
    getView()
        {
          return new 
    SuccessfullRegistrationView();
        }
      } 
    PHP Code:
      class UnSuccessfullRegistrationAction extends Action
      
    {
        var 
    $_errorList;

        function 
    UnSuccessfullRegistrationView($errors)
        {
          
    $this->_errorList $errors;
        }

        function 
    execute() { }

        function &
    getView()
        {
          return new 
    UnSuccessfullRegistrationView($this->_errorList);
        }
      } 
    PHP Code:
      class UnSuccessfullRegistrationView extends View
      
    {
        var 
    $_errorList;

        function 
    UnSuccessfullRegistrationView($errors)
        {
          
    $this->_errorList $errors;
        }

        function 
    render()
        {
          
    $tpl = new Template('/UnSuccessfullRegistration.tpl');
          
    $tpl->set('errors'$this->_errorList);
          echo 
    $tpl->getContents();
        }
      } 
    I'm a little suspicious about the View-classes. I think they are somewhat uneccessary since you can just move everything in the render()-function to the &getView()-function in the actions. In other words, is legal to construct the View in the Actions, MVC-wise? Or will I just mess up the layers that way?
    Also, I'm passing the list of errors from the validator 2 times before it actually gets displayed...bad design?

    Thanks in advance

  2. #2
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I do the form validation in the Controller layer, though I know some folk (SweatJs for one, I think..?!) do the validation in the Model instead.

    Passing the error messages to the View via the Controller seams reasonable, as does creating the View instance from the Controller. But like every other pattern, it's just a basis to develop from - nothing is set in stone, if that's any help?

  3. #3
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A form input is an HTTP request parameter, therefore the Controller is the part of the system that should know about that. Validation typically relates to the business logic of your domain model, so your Controller would pass the sanatized $_REQUEST variable to a method of your Model in order to determine if it is correct. IMO.

    PHP Code:
    class Controller {
      function 
    Validate(&$request) {
        
    $valid true;
        
    $model =& new Model;
        
    $valid &= $model->isValidFooBar($request->get('foobar'));
        
    $valid &= $model->isValidBaz($request->get('baz'));
        return 
    $valid;
      }

    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  4. #4
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I see two logical decisions to be made with a form submission, each leading to different kinds of response.

    (1) Is the request in a "valid form"?

    This is a more general check for "bad request syntax" (the 400 server response) covering all user input as well as the array in which the form was submitted. For the actual form sub, this means checking if it has the correct number of keys and correct key names. You can specify this pretty tightly (exactly in many cases). Values I'll come back to in a moment,

    If something is wrong, it's probably a hacking attempt. You'd maybe want to send a 400 page (or something less specific if you're playing your cards close to your chest) and maybe log the event.

    I agree this is definitely a controller responsibility. The controller knows which types of request are well-formed.

    (2) Is the submission processable ie are the values valid according to whatever rules there are for forms of this type?

    This is, I think, domain logic. The controller has to ask the model if the values are processable and then decide whether to process the submission or redisplay the form. With very simple checks - such as for integer values - the domain element isn't apparent and value validation looks like just another aspect of a "bad request syntax" check. However, complex domain logic might be required to validate the form - eg if you need to check if a flight is overbooked or a hire car will be available on a certain date. The controller doesn't (or shouldn't) know how to do this. The call comes from the controller but the actual value validation is performed in the model.

    Except it's not quite that clear cut. Some value rules should probably be applied in the controller, for example checks for certain types of XSS attacks like < script > & etc.

    This gives a two stage process for value validation: the controller knows how to check for badly formed requests with an armoury of simpler, more generally applicable rules and the model knows how to check for processable submissions using domain logic of whatever complexity is required.

    I think...

  5. #5
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:

    Off Topic slightly, but since McGruff is talking in some respect about attacks and preventitive measures, I thought I might post this url on sql injections?


    http://www.unixwiz.net/techtips/sql-injection.html

    Sql Injections By Example


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •