SlideShare a Scribd company logo
1 of 39
Download to read offline
Production agency specializing in Web
                                        PHP framework www.symfony.com
Development www.void.fr
Lhassan Baazzi
      Web Developper #php #Symfony2 at VOID




http://twitter.com/baazzi

http://www.facebook.com/jBinfo

http://plus.google.com/113667438028898816639
$0 Summary
$1- Why ?
$2- Goal
$3- How ?
$4- What is a constraint ?
$5- Basic validation example
$6- Supported constraints
$7- The validator service
$8- Validation and Forms
$9- Translation constraint messages
$10- Constraint targets
$11- Validation groups
$12- Validating values
$13- How to create a custom validation constraint ?
$1 Why ?


    Don't Trust
    User Input
$1 Why ?
1. Validation is a very common task in web
   applications.
2. Data entered in forms needs to be
   validated.
3. Data also needs to be validated before it
   is written into a database or passed to a
   web service.
$2 Goal

    The goal of validation is
   to tell you whether or not
     the data of an object is
              valid.
$3 How ?
 configure a list of rules (called constraints)
  that the object must follow in order to be
                      valid.

  These constraints can be specified via a
 number of different formats (YAML, XML,
          annotations, or PHP).
$4 Constraint


  a constraint is simply a PHP object that
      makes an assertive statement.
$5 Basic validation example
For example, to guarantee that the $name property is not
empty:
$5 Basic validation example
For example, to guarantee that the $name property is not
empty:




                                         Imports constraints
                                            namespace

                          Add NotBlank
                           constraint
$5 Basic validation example

 The Symfony2 validator is enabled by default, but you must
 explicitly enable annotations if you're using the annotation
 method to specify your constraints:
$6 Supported constraints
Basic Constraints      String Constraints           Collection Constraints
 NotBlank              Email                       Choice
 Blank                 MinLength                   Collection
 NotNull               MaxLength                   UniqueEntity
 Null                  Url                         Language
 True                  Regex                       Locale
 False                 Ip                          Country
 Type


Number Constraints   Date Constraints       File Constraints   Other Constraints
 Max                 Date                  File              Callback
 Min                 DateTime              Image             All
                      Time                                     Valid
$6 Supported constraints
Basic Constraints      String Constraints           Collection Constraints
 NotBlank              Email                       Choice
 Blank                 MinLength                   Collection
 NotNull               MaxLength                   UniqueEntity
 Null                  Url                         Language
 True                  Regex                       Locale
 False                 Ip                          Country
 Type


Number Constraints   Date Constraints       File Constraints   Other Constraints
 Max                 Date                  File              Callback
 Min                 DateTime              Image             All
                      Time                                     Valid
$7 The validator service


         To validate an object, use the
   validate method on the validator service.
$7 The validator service
The job of the validator:

     Is to read the constraints (i.e. rules) of a
     class and verify whether or not the data
     on the object satisfies those constraints.

       If validation fails, an array of errors is
                       returned.
$7 The validator service
$7 The validator service

     Each validation error (called a
  constraint violation), is represented
    by a ConstraintViolation object.




   ConstraintViolation: http://api.symfony.com/2.0/Symfony/Component/Validator/ConstraintViolation.html
$8 Validation and Forms

     Symfony's form library uses the
      validator service internally to
   validate the underlying object after
    values have been submitted and
                  bound.
$8 Validation and Forms


    The constraint violations on the
   object are converted into FieldError
   objects that can easily be displayed
             with your form.
$8 Validation and Forms
$9 Translating constraint messages

    Create a translation file under the
   validators catalog for the constraint
        messages, typically in the
   Resources/translations/ directory of
                the bundle.
$9 Translating constraint messages


                    Constraint message




                            Constraint message


                      Translation message
$10 Constraint targets

   Constraints can be applied to
   a class property (e.g. name)
    or a public getter method
        (e.g. getFullName)
$10 Constraint targets
Properties:
  The validator service allows you to validate private, protected or public
  properties.
  The example below shows you how to configure the $firstName property
  of an Author class to have at least 3 characters:
$10 Constraint targets

Getters:
 Constraints can also be applied to the return value of a
 method.
 Validator service allows you to add a constraint to any public
 method whose name starts with “get” or “is”. In this guide,
 both of these types of methods are referred to as “getters”.
$10 Constraint targets
Getters:
$10 Constraint targets

    Some constraints apply to the entire class being
                      validated.
    For example, the Callback constraint is a generic
 constraint that's applied to the class itself. When that
 class is validated, methods specified by that constraint
   are simply executed so that each can provide more
                     custom validation.
$11 Validation groups
Question:
   How to validate an object against
    only some of the constraints on
              that class ?
$11 Validation groups
Answer:
   Organize each constraint into one
   or more “validation groups”, and
   then apply validation against just
   one or more group of constraints.
$11 Validation groups
Example:
    Suppose you have a User class,
    which is used both when a user
  registers and when a user updates
   his/her contact information later:
$11 Validation groups
$11 Validation groups

  With this configuration, there are two validation
  groups:
   default: contains the constraints not
     assigned to any other group;
   registration: contains the constraints on the
     email and password fields only.
$11 Validation groups

  To tell the validator to use a specific group, pass
  one or more group names as the second
  argument to the validate() method:
$11 Validation groups
validation groups in forms:
      Controller:




      Form Class:
$12 Validating values

     you've seen how you can validate
    entire objects. But sometimes, you
   just want to validate a simple value -
     like to verify that a string is a valid
                email address.
$12 Validating values
verify that a string is a valid email address:
                                 Import constraint Email

                            Create the consraint

                                     Assigned the error message

                                                           Execute



                                     Check for errors
How to create a custom validation
$13   constraint ?



http://symfony.com/doc/current/cookbook/
     validation/custom_constraint.html
Questions ?

More Related Content

Similar to Symfony validation: How to validate user input in PHP applications

Unit testing for 40 square software
Unit testing for 40 square softwareUnit testing for 40 square software
Unit testing for 40 square softwareRuben Tan
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017Eoin Keary
 
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium MeetupSelenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium MeetupDave Haeffner
 
Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!DiUS
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava SchmidtJavaDayUA
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Brittany Ingram
 
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Codefresh
 
Chapter 14 - Web Design
Chapter 14 - Web DesignChapter 14 - Web Design
Chapter 14 - Web Designtclanton4
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 

Similar to Symfony validation: How to validate user input in PHP applications (20)

Unit testing for 40 square software
Unit testing for 40 square softwareUnit testing for 40 square software
Unit testing for 40 square software
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Selenium and The Grinder
Selenium and The GrinderSelenium and The Grinder
Selenium and The Grinder
 
Ebu class edgescan-2017
Ebu class edgescan-2017Ebu class edgescan-2017
Ebu class edgescan-2017
 
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium MeetupSelenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
 
Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!Deploy with Confidence using Pact Go!
Deploy with Confidence using Pact Go!
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava Schmidt
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Chapter14
Chapter14Chapter14
Chapter14
 
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
 
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
Codefresh + BlazeMeter Webinar: Continuous Testing for Containerized Applicat...
 
IoC with PHP
IoC with PHPIoC with PHP
IoC with PHP
 
Chapter 14 - Web Design
Chapter 14 - Web DesignChapter 14 - Web Design
Chapter 14 - Web Design
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Selenium
SeleniumSelenium
Selenium
 
ETL into Neo4j
ETL into Neo4jETL into Neo4j
ETL into Neo4j
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
selenium.ppt
selenium.pptselenium.ppt
selenium.ppt
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 

Recently uploaded

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Recently uploaded (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Symfony validation: How to validate user input in PHP applications

  • 1. Production agency specializing in Web PHP framework www.symfony.com Development www.void.fr
  • 2. Lhassan Baazzi Web Developper #php #Symfony2 at VOID http://twitter.com/baazzi http://www.facebook.com/jBinfo http://plus.google.com/113667438028898816639
  • 3.
  • 4. $0 Summary $1- Why ? $2- Goal $3- How ? $4- What is a constraint ? $5- Basic validation example $6- Supported constraints $7- The validator service $8- Validation and Forms $9- Translation constraint messages $10- Constraint targets $11- Validation groups $12- Validating values $13- How to create a custom validation constraint ?
  • 5. $1 Why ? Don't Trust User Input
  • 6. $1 Why ? 1. Validation is a very common task in web applications. 2. Data entered in forms needs to be validated. 3. Data also needs to be validated before it is written into a database or passed to a web service.
  • 7. $2 Goal The goal of validation is to tell you whether or not the data of an object is valid.
  • 8. $3 How ? configure a list of rules (called constraints) that the object must follow in order to be valid. These constraints can be specified via a number of different formats (YAML, XML, annotations, or PHP).
  • 9. $4 Constraint a constraint is simply a PHP object that makes an assertive statement.
  • 10. $5 Basic validation example For example, to guarantee that the $name property is not empty:
  • 11. $5 Basic validation example For example, to guarantee that the $name property is not empty: Imports constraints namespace Add NotBlank constraint
  • 12. $5 Basic validation example The Symfony2 validator is enabled by default, but you must explicitly enable annotations if you're using the annotation method to specify your constraints:
  • 13. $6 Supported constraints Basic Constraints String Constraints Collection Constraints  NotBlank  Email  Choice  Blank  MinLength  Collection  NotNull  MaxLength  UniqueEntity  Null  Url  Language  True  Regex  Locale  False  Ip  Country  Type Number Constraints Date Constraints File Constraints Other Constraints  Max  Date  File  Callback  Min  DateTime  Image  All  Time  Valid
  • 14. $6 Supported constraints Basic Constraints String Constraints Collection Constraints  NotBlank  Email  Choice  Blank  MinLength  Collection  NotNull  MaxLength  UniqueEntity  Null  Url  Language  True  Regex  Locale  False  Ip  Country  Type Number Constraints Date Constraints File Constraints Other Constraints  Max  Date  File  Callback  Min  DateTime  Image  All  Time  Valid
  • 15. $7 The validator service To validate an object, use the validate method on the validator service.
  • 16. $7 The validator service The job of the validator: Is to read the constraints (i.e. rules) of a class and verify whether or not the data on the object satisfies those constraints. If validation fails, an array of errors is returned.
  • 17. $7 The validator service
  • 18. $7 The validator service Each validation error (called a constraint violation), is represented by a ConstraintViolation object. ConstraintViolation: http://api.symfony.com/2.0/Symfony/Component/Validator/ConstraintViolation.html
  • 19. $8 Validation and Forms Symfony's form library uses the validator service internally to validate the underlying object after values have been submitted and bound.
  • 20. $8 Validation and Forms The constraint violations on the object are converted into FieldError objects that can easily be displayed with your form.
  • 22. $9 Translating constraint messages Create a translation file under the validators catalog for the constraint messages, typically in the Resources/translations/ directory of the bundle.
  • 23. $9 Translating constraint messages Constraint message Constraint message Translation message
  • 24. $10 Constraint targets Constraints can be applied to a class property (e.g. name) or a public getter method (e.g. getFullName)
  • 25. $10 Constraint targets Properties: The validator service allows you to validate private, protected or public properties. The example below shows you how to configure the $firstName property of an Author class to have at least 3 characters:
  • 26. $10 Constraint targets Getters: Constraints can also be applied to the return value of a method. Validator service allows you to add a constraint to any public method whose name starts with “get” or “is”. In this guide, both of these types of methods are referred to as “getters”.
  • 28. $10 Constraint targets Some constraints apply to the entire class being validated. For example, the Callback constraint is a generic constraint that's applied to the class itself. When that class is validated, methods specified by that constraint are simply executed so that each can provide more custom validation.
  • 29. $11 Validation groups Question: How to validate an object against only some of the constraints on that class ?
  • 30. $11 Validation groups Answer: Organize each constraint into one or more “validation groups”, and then apply validation against just one or more group of constraints.
  • 31. $11 Validation groups Example: Suppose you have a User class, which is used both when a user registers and when a user updates his/her contact information later:
  • 33. $11 Validation groups With this configuration, there are two validation groups:  default: contains the constraints not assigned to any other group;  registration: contains the constraints on the email and password fields only.
  • 34. $11 Validation groups To tell the validator to use a specific group, pass one or more group names as the second argument to the validate() method:
  • 35. $11 Validation groups validation groups in forms: Controller: Form Class:
  • 36. $12 Validating values you've seen how you can validate entire objects. But sometimes, you just want to validate a simple value - like to verify that a string is a valid email address.
  • 37. $12 Validating values verify that a string is a valid email address: Import constraint Email Create the consraint Assigned the error message Execute Check for errors
  • 38. How to create a custom validation $13 constraint ? http://symfony.com/doc/current/cookbook/ validation/custom_constraint.html