Symfony sfValidators:动态设置值是否需要?

Symfony sfValidators:动态设置值是否需要?

问题描述:

I have the following problem:

I have a form where a user can opt to toggle a switch (Yes/No).

If they select Yes, I hide a couple of fields on my template (because they will now automatically be calculated).

The catch is that now, a set of different fields are required to not be empty for the successful submission.

The first fields need not be optional after the switch is clicked (since they are merely hidden but still submitted), but the second set of fields must be non-empty.

Is there a simple way to get this dynamic validation behaviour using Symfony's sfValidator classes, or should I simply hack together a solution using jQuery?

我遇到以下问题: p>

我有一个用户表单 可以选择切换开关(是 code> / 否 code>)。 p>

如果他们选择是 code>,我 在我的模板上隐藏几个字段(因为它们现在将自动计算)。 p>

问题是现在 em>,需要一组不同的字段 成功提交不是空的。 p>

单击开关后,第一个字段不一定是可选的(因为它们只是隐藏但仍然提交),但第二组字段必须是非空的。 p>

有没有一种简单的方法可以使用Symfony的sfValidator类来获得这种动态验证行为,或者我应该使用jQuery简单地解决一个解决方案? p> div>

This sounds like a perfect case for the Callback constraint that already exists in Symfony. To quote the linked doc:

The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you're using validation with forms, this means that you can make these custom errors display next to a specific field, instead of simply at the top of your form.

This solves the backend, you still need to watch out for the required attributes of your fields so HTML5 validation can work properly.