如何在Play Framework 2.0中创建自定义验证器? [英] How to create a custom validator in Play Framework 2.0?
问题描述
Play 1.0附带一个基于 http://oval.sourceforge.net/ 的全功能验证框架。
Play 1.0 comes with a full featured validation framework base on http://oval.sourceforge.net/.
随着2.0的发布,我的自定义验证器不再起作用了。
With the release of 2.0, my custom validators do not work anymore.
如何创建自定义使用Play Framework 2.0的验证器?
How does one create custom validator using Play Framework 2.0 ?
推荐答案
在Play 2.0中,验证框架超出了数据的实际验证范围。 :
In Play 2.0, the validation framework extends beyond the actual validation of the data as it reaches to:
- 注释 - 使用'@'符号轻松声明验证限制
- 验证者 - 哪个实际上实现验证后面的逻辑
- 消息 - 显示参数化错误消息(符合i18)
- 最后,HTML帮助器 - 粘合所有以前的一起
- Annotations - to easily declare validation contraints using the '@' sign
- Validators - which actually implements to logic behind the validation
- Messages - to display parametrized error messages (i18 compliant)
- Finally, HTML helpers - that glue all the previous together
HTML助手是Play 2.0的新功能。在1.x中,Play已经非常擅长强制执行一个定义良好的验证框架。它功能强大且易于使用。然而,我们仍然需要将HTML表单和验证框架连接在一起。这对初学者来说可能有点混乱。
The HTML Helpers are something new to Play 2.0. In 1.x, Play was already pretty good at enforcing a well defined validation framework. It was powerful and easy to use. Yet we still had to wire the HTML form and the validation framework together. This could be a little confusing to the beginner.
使用Play 2.0,现在可以自动完成。
With Play 2.0, this is now done automatically.
但是让我们专注于答案并提供一些指导:我们将创建一个 AllUpperCase 验证器,在以下情况下生成错误:
But let's focus on the answer and provide some guidance: We will create an AllUpperCase validator, that generates an error either when:
- 输入不是字符串
- 输入为空
- 其中一个字符是小写的。
package myvalidators;
import javax.validation.*;
public class AllUpperCaseValidator
extends play.data.validation.Constraints.Validator<Object>
implements ConstraintValidator<AllUpperCase, Object> {
/* Default error message */
final static public String message = "error.alluppercase";
/**
* Validator init
* Can be used to initialize the validation based on parameters
* passed to the annotation.
*/
public void initialize(AllUpperCase constraintAnnotation) {}
/**
* The validation itself
*/
public boolean isValid(Object object) {
if(object == null)
return false;
if(!(object instanceof String))
return false;
String s = object.toString();
for(char c : s.toCharArray()) {
if(Character.isLetter(c) && Character.isLowerCase(c))
return false;
}
return true;
}
/**
* Constructs a validator instance.
*/
public static play.data.validation.Constraints.Validator<Object> alluppercase() {
return new AllUpperCaseValidator();
}
}
您可能会注意到的第一件事是导入:播放2.0确实符合JSR 303 - Bean Validation Framework。在此上下文中,验证器需要实现 ConstraintValidator 。在我们的例子中,将注释转换为类 AllUpperCase
(我们将在一分钟内介绍)和T作为通用对象
。
The first thing you may notice is the import: Play 2.0 indeed complies with JSR 303 - Bean Validation Framework. In this context, the validator needs to implement ConstraintValidator. Which in our case translates into the annotation as class AllUpperCase
(which we will introduce in a minute) and T as a generic Object
.
验证器是直接的:
我们定义了方法 public boolean isValid(Object object )返回一个布尔值,如果为true则验证通过。还有一个消息ID和一个实例化验证器的方法。
The validator is straighforward:
We defined the method public boolean isValid(Object object) that returns a boolean, if true the validation passed. There is also an message id and a method that instanciates the validator.
下面的类定义一个名为 @AllUpperCase
的注释,它不带任何参数,但强制执行先前定义的验证。提供与注释框架相关的详细信息超出了本文的范围。
The class below defines an annotation named @AllUpperCase
which takes no parameters but enforces the validation defined previously. Providing details related to the annotation framework is outside the scope of this post.
package myvalidators;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import javax.validation.*;
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = AllUpperCaseValidator.class)
@play.data.Form.Display(name="constraint.alluppercase")
public @interface AllUpperCase {
String message() default AllUpperCaseValidator.message;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
注意anotation如何粘合到拼图的其他部分。
Note how the anotation glues to the other pieces of the puzzle.
-
@Constraint
,一个JSR 303注释,链接到验证器 -
@ play.data.Form.Display
,将注释链接到play html帮助器。请注意,名称很重要:我们正在定义名为 alluppercase 的约束。 Play使用此信息调用方法public static play.data.validation.Constraints.Validator< Object>验证器上的alluppercase()
。 - 最后请注意,默认消息是在anotation界面中设置的。
@Constraint
, a JSR 303 annotation, links to the validator@play.data.Form.Display
, links the annotation to the play html helpers. Note that the name is important: we are defining a constraint named alluppercase. Play uses this information to call the methodpublic static play.data.validation.Constraints.Validator<Object> alluppercase()
on the Validator.- Finally note that the default message is set within the anotation interface.
我们现在有自定义验证器和注释
We now have our custom validator and annotation
import myvalidators.*;
public static class MyData {
@AllUpperCase
public String name;
}
描述用法超出了本文的范围,请查找工作样本在此网址
Describing the usage is outside the scope of this post, please find a working sample at this URL
这篇关于如何在Play Framework 2.0中创建自定义验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!