The definitive guide of Symfony 1.2

10.3. Form Validation

Note The features described in this section are deprecated since symfony 1.1 and only work if you enable the sfCompat10 plugin.

Chapter 6 explained how to use the validateXXX() methods in the action class to validate the request parameters. However, if you use this technique to validate a form submission, you will end up rewriting the same portion of code over and over. Symfony provides an alternative form-validation technique, relying on only a YAML file, instead of PHP code in the action class.

To demonstrate the form-validation features, let's first consider the sample form shown in Listing 10-18. It is a classic contact form, with name, email, age, and message fields.

Listing 10-18 - Sample Contact Form, in modules/contact/templates/indexSuccess.php

<?php echo form_tag('contact/send') ?>
  Name:    <?php echo input_tag('name') ?><br />
  Email:   <?php echo input_tag('email') ?><br />
  Age:     <?php echo input_tag('age') ?><br />
  Message: <?php echo textarea_tag('message') ?><br />
  <?php echo submit_tag() ?>
</form>

The principle of form validation is that if a user enters invalid data and submits the form, the next page should show an error message. Let's define what valid data should be for the sample form, in plain English:

  • The name field is required. It must be a text entry between 2 and 100 characters.
  • The email field is required. It must be a text entry between 2 and 100 characters, and it must be a valid e-mail address.
  • The age field is required. It must be an integer between 0 and 120.
  • The message field is required.

You could define more complex validation rules for the contact form, but these are just fine for a demonstration of the validation possibilities.

Note Form validation can occur on the server side and/or on the client side. The server-side validation is compulsory to avoid corrupting a database with wrong data. The client-side validation is optional, though it greatly enhances the user experience. The client-side validation is to be done with custom JavaScript.

10.3.1. Validators

You can see that the name and email fields in the example share common validation rules. Some validation rules appear so often in web forms that symfony packages the PHP code that implements them into validators. A validator is simple class that provides an execute() method. This method expects the value of a field as parameter, and returns true if the value is valid and false otherwise.

Symfony ships with several validators (described in the "Standard Symfony Validators" section later in this chapter), but let's focus on the sfStringValidator for now. This validator checks that an input is a string, and that its size is between two specified character amounts (defined when calling the initialize() method). That's exactly what is required to validate the name field. Listing 10-19 shows how to use this validator in a validation method.

Listing 10-19 - Validating Request Parameters with Reusable Validators, in modules/contact/action/actions.class.php

public function validateSend($request)
{
  $name = $request->getParameter('name');

  // The name field is required
  if (!$name)
  {
    $this->getRequest()->setError('name', 'The name field cannot be left blank');

    return false;
  }

  // The name field must be a text entry between 2 and 100 characters
  $myValidator = new sfStringValidator($this->getContext(), array(
    'min'       => 2,
    'min_error' => 'This name is too short (2 characters minimum)',
    'max'       => 100,
    'max_error' => 'This name is too long. (100 characters maximum)',
  ));
  if (!$myValidator->execute($name, $error))
  {
    return false;
  }

  return true;
}

If a user submits the form in Listing 10-18 with the value a in the name field, the execute() method of the sfStringValidator will return false (because the string length is less than the minimum of two characters). The validateSend() method will then fail, and the handleErrorSend() method will be called instead of the executeSend() method.

Tip The setError() method of the sfRequest method gives information to the template so that it can display an error message (as explained in the "Displaying the Error Messages in the Form" section later in this chapter). The validators set the errors internally, so you can define different errors for the different cases of nonvalidation. That's the purpose of the min_error and max_error initialization parameters of the sfStringValidator.

All the rules defined in the example can be translated into validators:

  • name: sfStringValidator (min=2, max=100)
  • email: sfStringValidator (min=2, max=100) and sfEmailValidator
  • age: sfNumberValidator (min=0, max=120)

The fact that a field is required is not handled by a validator.

10.3.2. Validation File

You could easily implement the validation of the contact form with validators in the validateSend() method PHP, but that would imply repeating a lot of code. Symfony offers an alternative way to define validation rules for a form, and it involves YAML. For instance, Listing 10-20 shows the translation of the name field validation rules, and its results are equivalent to those of Listing 10-19.

Listing 10-20 - Validation File, in modules/contact/validate/send.yml

fields:
  name:
    required:
      msg:       The name field cannot be left blank
    sfStringValidator:
      min:       2
      min_error: This name is too short (2 characters minimum)
      max:       100
      max_error: This name is too long. (100 characters maximum)

In a validation file, the fields header lists the fields that need to be validated, if they are required, and the validators that should be tested on them when a value is present. The parameters of each validator are the same as those you would use to initialize the validator manually. A field can be validated by as many validators as necessary.

Note The validation process doesn't stop when a validator fails. Symfony tests all the validators and declares the validation failed if at least one of them fails. And even if some of the rules of the validation file fail, symfony will still look for a validateXXX() method and execute it. So the two validation techniques are complementary. The advantage is that, in a form with multiple failures, all the error messages are shown.

Validation files are located in the module validate/ directory, and named by the action they must validate. For example, Listing 10-19 must be stored in a file called validate/send.yml.

10.3.3. Redisplaying the Form

By default, symfony looks for a handleErrorSend() method in the action class whenever the validation process fails, or displays the sendError.php template if the method doesn't exist.

The usual way to inform the user of a failed validation is to display the form again with an error message. To that purpose, you need to override the handleErrorSend() method and end it with a redirection to the action that displays the form (in the example, module/index), as shown in Listing 10-21.

Listing 10-21 - Displaying the Form Again, in modules/contact/actions/actions.class.php

class ContactActions extends sfActions
{
  public function executeIndex()
  {
    // Display the form
  }

  public function handleErrorSend()
  {
    $this->forward('contact', 'index');
  }

  public function executeSend()
  {
    // Handle the form submission
  }
}

If you choose to use the same action to display the form and handle the form submission, then the handleErrorSend() method can simply return sfView::SUCCESS to redisplay the form from sendSuccess.php, as shown in Listing 10-22.

Listing 10-22 - A Single Action to Display and Handle the Form, in modules/contact/actions/actions.class.php

class ContactActions extends sfActions
{
  public function executeSend()
  {
    if (!$this->getRequest()->isMethod('post'))
    {
      // Prepare data for the template

      // Display the form
      return sfView::SUCCESS;
    }
    else
    {
      // Handle the form submission
      ...
      $this->redirect('mymodule/anotheraction');
    }
  }
  public function handleErrorSend()
  {
    // Prepare data for the template

    // Display the form
    return sfView::SUCCESS;
  }
}

The logic necessary to prepare the data can be refactored into a protected method of the action class, to avoid repeating it in the executeSend() and handleErrorSend() methods.

With this new configuration, when the user types an invalid name, the form is displayed again, but the entered data is lost and no error message explains the reason of the failure. To address the last issue, you must modify the template that displays the form, to insert error messages close to the faulty field.

10.3.4. Displaying the Error Messages in the Form

The error messages defined as validator parameters are added to the request when a field fails validation (just as you can add an error manually with the setError() method, as in Listing 10-19). The sfRequest object provides two useful methods to retrieve the error message: hasError() and getError(), which each expect a field name as parameter. In addition, you can display an alert at the top of the form to draw attention to the fact that one or many of the fields contain invalid data with the hasErrors() method. Listings 10-23 and 10-24 demonstrate how to use these methods.

Listing 10-23 - Displaying Error Messages at the Top of the Form, in templates/indexSuccess.php

<?php if ($sf_request->hasErrors()): ?>
  <p>The data you entered seems to be incorrect.
  Please correct the following errors and resubmit:</p>
  <ul>
  <?php foreach($sf_request->getErrors() as $name => $error): ?>
    <li><?php echo $name ?>: <?php echo $error ?></li>
  <?php endforeach; ?>
  </ul>
<?php endif; ?>

Listing 10-24 - Displaying Error Messages Inside the Form, in templates/indexSuccess.php

<?php echo form_tag('contact/send') ?>
  <?php if ($sf_request->hasError('name')): ?>
    <?php echo $sf_request->getError('name') ?> <br />
  <?php endif; ?>
  Name:    <?php echo input_tag('name') ?><br />
  ...
  <?php echo submit_tag() ?>
</form>

The conditional use of the getError() method in Listing 10-23 is a bit long to write. That's why symfony offers a form_error() helper to replace it, provided that you declare the use of its helper group, Validation. Listing 10-25 replaces Listing 10-24 by using this helper.

Listing 10-25 - Displaying Error Messages Inside the Form, the Short Way

<?php use_helper('Validation') ?>
<?php echo form_tag('contact/send') ?>

           <?php echo form_error('name') ?><br />
  Name:    <?php echo input_tag('name') ?><br />
  ...
  <?php echo submit_tag() ?>
</form>

The form_error() helper adds a special character before and after each error message to make the messages more visible. By default, the character is an arrow pointing down (corresponding to the &darr; entity), but you can change it in the settings.yml file:

all:
  .settings:
    validation_error_prefix:    ' &darr;&nbsp;'
    validation_error_suffix:    ' &nbsp;&darr;'

In case of failed validation, the form now displays errors correctly, but the data entered by the user is lost. You need to repopulate the form to make it really user-friendly.

10.3.5. Repopulating the Form

As the error handling is done through the forward() method (shown in Listing 10-21), the original request is still accessible, and the data entered by the user is in the request parameters. So you could repopulate the form by adding default values to each field, as shown in Listing 10-26.

Listing 10-26 - Setting Default Values to Repopulate the Form When Validation Fails, in templates/indexSuccess.php

<?php use_helper('Validation') ?>
<?php echo form_tag('contact/send') ?>
           <?php echo form_error('name') ?><br />
  Name:    <?php echo input_tag('name', $sf_params->get('name')) ?><br />
           <?php echo form_error('email') ?><br />
  Email:   <?php echo input_tag('email', $sf_params->get('email')) ?><br />
           <?php echo form_error('age') ?><br />
  Age:     <?php echo input_tag('age', $sf_params->get('age')) ?><br />
           <?php echo form_error('message') ?><br />
  Message: <?php echo textarea_tag('message', $sf_params->get('message')) ?><br />
  <?php echo submit_tag() ?>
</form>

But once again, this is quite tedious to write. Symfony provides an alternative way of triggering repopulation for all the fields of a form, directly in the YAML validation file, without changing the default values of the elements. Just enable the fillin: feature for the form, with the syntax described in Listing 10-27.

Listing 10-27 - Activating fillin to Repopulate the Form When Validation Fails, in validate/send.yml

fillin:
  enabled: true  # Enable the form repopulation
  param:
    name: test  # Form name, not needed if there is only one form in the page
    skip_fields:   [email]  # Do not repopulate these fields
    exclude_types: [hidden, password] # Do not repopulate these field types
    check_types:   [text, checkbox, radio, select, hidden] # Do repopulate these
    content_type:  html  # html is the tolerant default. Other option is xml and xhtml (same as xml but without xml prolog)

By default, the automatic repopulation works for text inputs, check boxes, radio buttons, text areas, and select components (simple and multiple), but it does not repopulate password or hidden tags. The fillin feature doesn't work for file tags.

Note The fillin feature works by parsing the response content in XML just before sending it to the user. By default fillin will output HTML.

If you want to have fillin to output XHTML you have to set param: content_type: xml. If the response is not a strictly valid XHTML document fillin will not work.

The third available content_type is xhtml which is the same as xml but it removes the xml prolog from the response which causes quirks mode in IE6.

You might want to transform the values entered by the user before writing them back in a form input. Escaping, URL rewriting, transformation of special characters into entities, and all the other transformations that can be called through a function can be applied to the fields of your form if you define the transformation under the converters: key, as shown in Listing 10-28.

Listing 10-28 - Converting Input Before fillin, in validate/send.yml

fillin:
  enabled: true
  param:
    name: test
    converters:         # Converters to apply
      htmlentities:     [first_name, comments]
      htmlspecialchars: [comments]

10.3.6. Standard Symfony Validators

Symfony contains some standard validators that can be used for your forms:

  • sfStringValidator
  • sfNumberValidator
  • sfEmailValidator
  • sfUrlValidator
  • sfRegexValidator
  • sfCompareValidator
  • sfPropelUniqueValidator
  • sfFileValidator
  • sfCallbackValidator

Each has a default set of parameters and error messages, but you can easily override them through the initialize() validator method or in the YAML file. The following sections describe the validators and show usage examples.

10.3.6.1. String Validator ###

sfStringValidator allows you to apply string-related constraints to a parameter.

sfStringValidator:
  values:       [foo, bar]
  values_error: The only accepted values are foo and bar
  insensitive:  false  # If true, comparison with values is case insensitive
  min:          2
  min_error:    Please enter at least 2 characters
  max:          100
  max_error:    Please enter less than 100 characters

10.3.6.2. Number Validator ###

sfNumberValidator verifies if a parameter is a number and allows you to apply size constraints.

sfNumberValidator:
  nan_error:    Please enter an integer
  min:          0
  min_error:    The value must be at least zero
  max:          100
  max_error:    The value must be less than or equal to 100

10.3.6.3. E-Mail Validator ###

sfEmailValidator verifies if a parameter contains a value that qualifies as an e-mail address.

sfEmailValidator:
  strict:       true
  email_error:  This email address is invalid

RFC822 defines the format of e-mail addresses. However, it is more permissive than the generally accepted format. For instance, me@localhost is a valid e-mail address according to the RFC, but you probably don't want to accept it. When the strict parameter is set to true (its default value), only e-mail addresses matching the pattern [email protected] are valid. When set to false, RFC822 is used as a rule.

10.3.6.4. URL Validator ###

sfUrlValidator checks if a field is a correct URL.

sfUrlValidator:
  url_error:    This URL is invalid

10.3.6.5. Regular Expression Validator ###

sfRegexValidator allows you to match a value against a Perl-compatible regular expression pattern.

sfRegexValidator:
  match:        No
  match_error:  Posts containing more than one URL are considered as spam
  pattern:      /http.*http/si

The match parameter determines if the request parameter must match the pattern to be valid (value Yes) or match the pattern to be invalid (value No).

10.3.6.6. Compare Validator ###

sfCompareValidator compares two different request parameters. It is very useful for password checks.

fields:
  password1:
    required:
      msg:      Please enter a password
  password2:
    required:
      msg:      Please retype the password
    sfCompareValidator:
      check:    password1
      compare_error: The two passwords do not match

The check parameter contains the name of the field that the current field must match to be valid.

By default, the validator checks the equality of the parameters. You can change this behavior be specifying an operator parameter. Available operators are: >, >=, <, <=, == and !=.

10.3.6.7. Propel Unique Validator ###

sfPropelUniqueValidator validates that the value of a request parameter doesn't already exist in your database. It is very useful for unique indexes.

fields:
  nickname:
    sfPropelUniqueValidator:
      class:        User
      column:       login
      unique_error: This login already exists. Please choose another one.

In this example, the validator will look in the database for a record of class User where the login column has the same value as the field to validate.

Caution sfPropelUniqueValidator is susceptible to race conditions. Although unlikely, in multiuser environments, the result may change the instant it returns. You should still be ready to handle a duplicate INSERT error.

10.3.6.8. File Validator ###

sfFileValidator applies format (an array of mime-types) and size constraints to file upload fields.

fields:
  image:
    file:       True
    required:
      msg:      Please upload an image file
    sfFileValidator:
      mime_types:
        - 'image/jpeg'
        - 'image/png'
        - 'image/x-png'
        - 'image/pjpeg'
      mime_types_error: Only PNG and JPEG images are allowed
      max_size:         512000
      max_size_error:   Max size is 512Kb

Be aware that the file attribute must be set to True for the field, and the template must declare the form as multipart.

10.3.6.9. Callback Validator ###

sfCallbackValidator delegates the validation to a third-party callable method or function to do the validation. The callable method or function must return true or false.

fields:
  account_number:
    sfCallbackValidator:
      callback:      is_numeric
      invalid_error: Please enter a number.
  credit_card_number:
    sfCallbackValidator:
      callback:      [myTools, validateCreditCard]
      invalid_error: Please enter a valid credit card number.

The callback method or function receives the value to be validated as a first parameter. This is very useful when you want to reuse existing methods of functions, rather than create a full validator class.

Tip You can also write your own validators, as described in the "Creating a Custom Validator" section later in this chapter.

10.3.7. Named Validators

If you see that you need to repeat a validator class and its settings, you can package it under a named validator. In the example of the contact form, the email field needs the same sfStringValidator parameters as the name field. So you can create a myStringValidator named validator to avoid repeating the same settings twice. To do so, add a myStringValidator label under the validators: header, and set the class and param keys with the details of the named validator you want to package. You can then use the named validator just like a regular one in the fields section, as shown in Listing 10-29.

Listing 10-29 - Reusing Named Validators in a Validation File, in validate/send.yml

validators:
  myStringValidator:
    class: sfStringValidator
    param:
      min:       2
      min_error: This field is too short (2 characters minimum)
      max:       100
      max_error: This field is too long (100 characters maximum)

fields:
  name:
    required:
      msg:       The name field cannot be left blank
    myStringValidator:
  email:
    required:
      msg:       The email field cannot be left blank
    myStringValidator:
    sfEmailValidator:
      email_error:  This email address is invalid

10.3.8. Restricting the Validation to a Method

By default, the validators set in a validation file are run when the action is called with the POST method. You can override this setting globally or field by field by specifying another value in the methods key, to allow a different validation for different methods, as shown in Listing 10-30.

Listing 10-30 - Defining When to Test a Field, in validate/send.yml

methods:         [post]     # This is the default setting

fields:
  name:
    required:
      msg:       The name field cannot be left blank
    myStringValidator:
  email:
    methods:     [post, get] # Overrides the global methods settings
    required:
      msg:       The email field cannot be left blank
    myStringValidator:
    sfEmailValidator:
      email_error:  This email address is invalid

10.3.9. What Does a Validation File Look Like?

So far, you have seen only bits and pieces of a validation file. When you put everything together, the validation rules find a clear translation in YAML. Listing 10-31 shows the complete validation file for the sample contact form, corresponding to all the rules defined earlier in the chapter.

Listing 10-31 - Sample Complete Validation File

fillin:
  enabled:      true

validators:
  myStringValidator:
    class: sfStringValidator
    param:
      min:       2
      min_error: This field is too short (2 characters minimum)
      max:       100
      max_error: This field is too long (100 characters maximum)

fields:
  name:
    required:
      msg:       The name field cannot be left blank
    myStringValidator:
  email:
    required:
      msg:       The email field cannot be left blank
    myStringValidator:
    sfEmailValidator:
      email_error:  This email address is invalid
  age:
    sfNumberValidator:
      nan_error:    Please enter an integer
      min:          0
      min_error:    "You're not even born. How do you want to send a message?"
      max:          120
      max_error:    "Hey, grandma, aren't you too old to surf on the Internet?"
  message:
    required:
      msg:          The message field cannot be left blank