Play Framework 2:分别验证单个模型字段的最佳方法 [英] Play Framework 2: Best way of validating individual model fields separately
问题描述
对于此示例,我们假设用户只想更新其在线个人资料的名字。
For this example, lets assume the user would like to update just the first name of his online profile.
表格:
<form data-ng-submit="updateFirstName()">
<label for="firstName">First name<label>
<input type="text" name="title" data-ng-model="firstName">
<button type="submit">Update first name</button>
</form>
控制器:
public class UsersController {
public static Result updateFirstName() {
Form<User> filledForm = Form.form(User.class).bindFromRequest();
// TODO: Validate firstName
// if hasErrors() return bad request with errors as json
// else save and return ok()
}
}
型号:
@Entity
public class User extends Model {
@Id
public Long id;
@Constraints.Required
public String firstName;
@Constraints.Required
public String lastName;
}
如何根据模型约束一次只验证一个字段并返回任何产生的错误消息以json的形式返回?这是一个非常简单的例子,真实的东西将有许多字段(一些非常复杂)以及每个字段的形式。
How would one validate just one field at a time against the models constraints and return any resulting error messages back as json? This is quite a simple example, the real thing will have many fields (some very complex) together with a form for each.
推荐答案
Play的内置验证注释符合Java bean验证规范(JSR-303)。因此,您可以使用规范中记录的验证组功能:
Play's in-built validation annotations conform to the Java bean validation specification (JSR-303). As a result, you can use the validation groups feature documented in the spec:
@Entity
public class User extends Model {
// Use this interface to mark out the subset of validation rules to run when updating a user's first name
public interface FirstNameStep {}
@Id
public Long id;
@Required(groups = FirstNameStep.class)
public String firstName;
// This isn't required when updating a user's first name
@Required
public String lastName;
}
控制器
Controller
public class UsersController {
public static Result updateFirstName() {
// Only run the validation rules that need to hold when updating a user's first name
Form<User> filledForm = Form.form(User.class, User.FirstNameStep.class).bindFromRequest();
if (form.hasErrors()) {
// return bad request with errors as json
}
// else save and return ok()
}
}
验证组适用于您的情况,其中您有相同的模型对象支持不同的表单,并且您希望为表单强制执行不同的验证规则。
Validation groups are intended for your situation, where you have the same model object backing different forms, and you want to enforce different validation rules for the forms.
这篇关于Play Framework 2:分别验证单个模型字段的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!