Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate single form field only in Symfony2

I'm looking for a way to validate just a single field (object property) against the constraints specified in the annotations of a particular entity.

The goal is to send an AJAX request after the "onBlur" event of a form field, asking the server to validate this single field only, and - depending on the response - add a small "OK" image next to this field or an error message.

I don't want to validate the whole entity.

I wonder what's the best approach for this problem? Thanks for any tips.

like image 624
grzechoo Avatar asked Dec 06 '11 14:12

grzechoo


1 Answers

The Validator class has the validateProperty method. You can use it like this:

$violations = $this->get('validator')->validateProperty($entity, 'propertyName');
if (count($violations)) {
    // the property value is not valid
}

Or, if the value is not set in the entity, you can use the validatePropertyValue method:

$violations = $this->get('validator')->validatePropertyValue($entity, 'propertyName', $propertyValue);
if (count($violations)) {
    // the property value is not valid
}
like image 107
Elnur Abdurrakhimov Avatar answered Oct 21 '22 02:10

Elnur Abdurrakhimov