Reputation: 1093
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.
Upvotes: 12
Views: 6757
Reputation: 44851
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
}
Upvotes: 23
Reputation: 13214
Have a look at validation groups. I think this is what you need. You could add a group "ajax" or and just adding the one constraint to it. Then tell the validator to use that group. THe symfony2 docs have an example included.
Upvotes: 5