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.

2 Answers 2

24

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.