仅在Symfony2中验证单个表单字段

时间:2022-10-16 15:08:27

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.

目标是在表单字段的“onBlur”事件之后发送一个AJAX请求,要求服务器仅验证此单个字段,并且 - 根据响应 - 在此字段旁边添加一个小的“OK”图像或错误信息。

I don't want to validate the whole entity.

我不想验证整个实体。

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

我想知道这个问题的最佳方法是什么?谢谢你的任何提示。

2 个解决方案

#1


18  

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

Validator类具有validateProperty方法。你可以像这样使用它:

$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:

或者,如果未在实体中设置该值,则可以使用validatePropertyValue方法:

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

#2


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.

看看验证组。我想这就是你需要的。您可以添加组“ajax”或只添加一个约束。然后告诉验证者使用该组。 symfony2文档中包含一个示例。

#1


18  

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

Validator类具有validateProperty方法。你可以像这样使用它:

$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:

或者,如果未在实体中设置该值,则可以使用validatePropertyValue方法:

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

#2


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.

看看验证组。我想这就是你需要的。您可以添加组“ajax”或只添加一个约束。然后告诉验证者使用该组。 symfony2文档中包含一个示例。