我想知道我是否可以在需要时忽略 Play 标准验证。例如,假设我有一个名为 Car 的实体,就像
@Entity
public class Car{
@Id
private Long id;
@Required
private String model;
@Required
private String hiddenField; //important but doesn't appear in some cases (some usecases)
}
为了说得更清楚
案例1
@(carForm : Form[Car])
@import helper._
@form(routes.controller.foo.bar) {
@inputText(carForm("model"))
<input type="submit">
}
案例2
@(carForm : Form[Car])
@import helper._
@form(routes.controller.foo.bar) {
@inputText(carForm("model"))
@inputText(carForm("hiddenField"))
<input type="submit">
}
然后我有一个 Play.data.Form 对象,它有错误,因为我没有填充模型或作为示例给出的隐藏字段。但是,实际上,我有一些情况,这个隐藏甚至没有出现(情况1),我的意思是,没有所谓的输入,因为当时不允许用户编辑它。因此,如果我有两个用例,第一个用例中所有输入都在那里并且应该被填充,但另一个用例没有“hiddenField”输入,但是,尽管如此,我的模型仍然需要它,并且,当然,没有它提交的表单也会出错,我该怎么办?我该如何处理呢?我有一个模型,但验证在一种情况下可能与另一种情况不同,我希望它是服务器端,而不是 jquery 或纯 javascript。
我试图通过丢弃错误 (假设它是从案例 1 提交的)
MyForm<Car> myCarForm = Form.form(Car.class).bindFromRequest();
//it has errors, sure it does, hiddenField was required and that field didn't even exist at screen.
myCarForm.discardErrors(); //ok, error hashmap is empty right now
myCarForm.get(); // anyway, no value here.
//myCarForm.data(); //for sure i could retrieve field by field and remount object that way, but that looks hacky and hardworking
那么,有什么解决办法吗?谢谢大家
最佳答案
我是在阅读《Play for Java》一书时得到的。
6.4.2 部分验证
一个常见的用例是对同一对象有多个验证约束 模型。因为我们正在定义对对象模型的约束,所以通常有 引用同一对象模型的多种形式。但这些形式可能有不同 验证约束。为了说明这个用例,我们可以想象一个简单的向导 用户通过两步输入新产品:
- 1 用户输入产品名称并提交表单。
- 2 用户输入产品 EAN 编号和说明。
我们可以在第 2 步验证产品名称,但会显示错误消息 因为那时的产品名称会很奇怪。幸运的是,Play 可以让你执行 部分验证。对于每个带注释的值,我们需要指出它在哪一步 适用。我们可以借助注释中的 groups 属性来做到这一点。 让我们更改我们的产品模型类来做到这一点:
public Product extends Model {
public interface Step1{}
public interface Step2{}
@Required(groups = Step1.class)
public String name;
@Required(groups = Step2.class)
public String ean;
}
然后,在 Controller
// We re//strict the validation to the Step1 "group"
Form<Product> productForm =
form(Product.class, Product.Step1.class).bindFromRequest();
谢谢!
关于forms - 忽略不同 View 下的 Play Framework 表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24498053/