setter之后的Bean验证?

时间:2011-10-08 23:36:46

标签: bean-validation

我想验证修剪过的字符串长度,例如:

@Size(min = 5, max = 20, message = "Please enter a valid username (5-20 characters)")
String userName;

给定用户名foo(6个字符),它将在setter方法中被修剪为foo(3个字符),但是,对原始输入进行验证似乎有点无用。

1 个答案:

答案 0 :(得分:3)

您可以编写自己的约束来包装预期的验证逻辑,而不是更改验证过程。

我在auto-trader-spring-spike项目中找到了@TrimmedSize注释的实现:

package com.autotrader.frameworks;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;

@Documented
@Constraint(validatedBy = TrimmedSizeValidator.class)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface TrimmedSize {
    String message() default "size too small";

    Class<?>[] groups() default {};

    int min() default 0;

    Class<? extends Payload>[] payload() default {};
}

验证员:

package com.autotrader.frameworks;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class TrimmedSizeValidator implements ConstraintValidator<TrimmedSize, String> {

    private int length;

    public void initialize(TrimmedSize trimmedSize) {
        length = trimmedSize.min();
    }

    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null || value.length() == 0) {
            return false;
        }
        return value.trim().length() >= length;
    }
}

它使用Apache License 2.0,但即便如此,您可以在看到它后从头开始编写此代码。