Validation with Symfony2 from a Drupal Perspective: DrupalCon Austin Session Notes

Tuesday, June 3, 2014
Wayne Eaker
Module Developers
Validation with Symfony2 from a Drupal Perspective: DrupalCon Austin Session Notes
  • Symfony is a set of reusable components. Drupal 8 uses 12 of these components.
  • Install with composer: "symfony/validator"

Validator Object

  • $validator = Validation::createValidator();
    $validator->validateValue('[email protected]', new Email()); // Email is a constraint class

  • Combine constraints: $validator->value('wayne', array(new Length('min' => 5, 'max' => 15)), new Regex(array('pattern' => '/XXXX/'))

  • Can also validate whole objects.
  • validateValue(), validateProperty($user, 'email'), validationPropertyValue($user, 'email', '[email protected]'), validate($user)
  • ConstraintViolationList is a collection of validation failures

Constraint and ConstraintValidator

  • public properties = options for a Constraint subclass
  • class Regex, class RegexValidator. The Validator does the logic of validating in the validate() function
  • BasicConstraints: NotBlank(), Blank(), NotNull(), Null(), True(), False(), Url(), Ip(), Length(), Email()
  • Comparison Constraints
  • Date and Time constraints
  • Number and Financial Constraints: Currency(), CardScheme(), Iban(), Isbn()
  • Image Constraints: mimetypes, size, width, height
  • Collection Constraints: check all the values in an array

Object Validation Mapping

  • Can be definied in PHP, YML, XML, or Annotations
  • For each property of the object, you define the validation constratints in a validation builder
  • Annotations allow you to keep the validation rules right with the properties in the file.
  • Can have the validator validate sub-objects automatically.
  • Can apply constraints on methods as well as properties
  • You can apply Callback constraints to use methods to validate a property

Validation Groups

  • Allows for validation rules to change based on context
  • For example, user registration versus user edit profile
  • Group Sequence allows you to break validation into steps

Slides, for Example Code