@@ -762,6 +762,52 @@ Of course, you'll usually work with validation indirectly through the form
762
762
library. For information on how to use validation groups inside forms, see
763
763
:ref: `book-forms-validation-groups `.
764
764
765
+ .. index ::
766
+ single: Validation; Validating raw values
767
+
768
+ Validating Values and Arrays
769
+ ----------------------------
770
+
771
+ So far, you've seen how you can validate entire objects. But sometimes, you
772
+ just want to validate a simple value - like to verify that a string is a valid
773
+ email address. This is actually pretty easy to do. From inside a controller,
774
+ it looks like this::
775
+
776
+ // add this to the top of your class
777
+ use Symfony\Component\Validator\Constraints\Email;
778
+
779
+ public function addEmailAction($email)
780
+ {
781
+ $emailConstraint = new Email();
782
+ // all constraint "options" can be set this way
783
+ $emailConstraint->message = 'Invalid email address';
784
+
785
+ // use the validator to validate the value
786
+ $errorList = $this->get('validator')->validateValue($email, $emailConstraint);
787
+
788
+ if (count($errorList) == 0) {
789
+ // this IS a valid email address, do something
790
+ } else {
791
+ // this is *not* a valid email address
792
+ $errorMessage = $errorList[0]->getMessage()
793
+
794
+ // do somethign with the error
795
+ }
796
+
797
+ // ...
798
+ }
799
+
800
+ By calling ``validateValue `` on the validator, you can pass in a raw value and
801
+ the constraint object that you want to validate that value against. A full
802
+ list of the available constraints - as well as the full class name for each
803
+ constraint - is available in the :doc: `constraints reference</reference/constraints> `
804
+ section .
805
+
806
+ The ``validateValule `` method returns a :class: `Symfony\\ Component\\ Validator\\ ConstraintViolationList `
807
+ object, which acts just like an array of errors. Each error in the collection
808
+ is a :class: `Symfony\\ Component\\ Validator\\ ConstraintViolation ` object,
809
+ which holds the error message on its `getMessage ` method.
810
+
765
811
Final Thoughts
766
812
--------------
767
813
0 commit comments