12

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.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
grzechoo
  • 1,093
  • 3
  • 11
  • 20

2 Answers2

23

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
}
Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
5

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.

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78