http://www.iteye.com/topic/165340
http://www.duduwolf.com/wiki/2007/345.html
需要validation-api和hiberante-validation,
spring的验证是基于
JSR-303
的
validation-api
是jsr303的接口,而hiberante-validation是验证接口的实现。
@RequestMapping("/valid")
public String valid(@ModelAttribute("vm") [color=red]@Valid[/color] ValidModel vm, BindingResult result) {
if (result.hasErrors()) {
return "validResult";
}
return "helloworld";
}
自定义jsr 303格式的annotation
可以参考hibernate validator 4 reference 手册中3.1节
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = FixLengthImpl.class)
public @interface FixLength {
int length();
String message() default "{net.zhepu.web.valid.fixlength.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证实现类
public class FixLengthImpl implements ConstraintValidator<FixLength, String> {
private int length;
@Override
public boolean isValid(String validStr,
ConstraintValidatorContext constraintContext) {
if (validStr.length() != length) {
return false;
} else {
return true;
}
}
@Override
public void initialize(FixLength fixLen) {
this.length = fixLen.length();
}
}