1

birthYear「ユーザーの年齢は 50 歳未満である必要があります」という方法でフィールドを検証したい。

したがって、次のように JSR-303 アノテーション検証を使用したいと思います。

@Max(Calendar.getInstance().get(Calendar.YEAR) - 50)
private int birthYear;

しかし、コンパイラは「属性値は定数でなければなりません」と言います。

このような簡単な方法でそれを行う方法はありますか?それとも、そのために独自のバリデーターを実装する必要がありますか?

4

3 に答える 3

1

The problem is that the annotations params need to have a value that can be resolved at compile time, but the Call to Calendar.getInstance().get(Calendar.YEAR) can only be resolved at runtime thus the compiler error.

You are better off in this type of situation to write the validation logic in the setter logic, something like

public  void setBirthYear( int year){ 
   if( Calendar.getInstance().get(Calendar.YEAR) - year < 50) {
   {
     throw IllegalAgumentException()
   }
   this.birthYear = year;
} 

The alternative is that you can write a custom JSR 303 Annotation something like @VerifyAge(maxAge=50) then in the handler for the annotation you can check that the value is less than 50.

See http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html for details on how to write a custom validation annotation.

于 2013-09-16T16:57:07.793 に答える
0

エラー メッセージが示すように、注釈値に式を含めることはできないため、カスタム検証注釈を使用する必要があります。

これを行うのは比較的簡単です:

注釈

@Constraint(validatedBy = AgeConstraintValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface MaxAge {

/**
 * The age against which to validate.
 */
int value();

String message() default "com.mycompany.validation.MaxAge.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

制約バリデーター

public class AgeConstraintValidator implements ConstraintValidator<MaxAge, Integer> {

private int maximumAge;

@Override
public void initialize(MaxAge constraintAnnotation) {
    this.maximumAge = constraintAnnotation.value();
}

@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    return value.intValue() <= this.maximumAge;
}

}

次に、フィールドに注釈を付けるだけ@MaxAge(50)で機能するはずです。

于 2013-09-16T17:04:22.520 に答える
0

Spring Framework を使用している場合は、Spring Expression Language (SpEL) を使用できます。SpEL に基づく JSR-303 バリデータを提供する小さなライブラリを作成しました。https://github.com/jirutka/validator-springをご覧ください。

このライブラリを使用すると、次のように検証を記述できます。

@SpELAssert("#this < T(java.util.Calendar).getInstance().get(T(java.util.Calendar).YEAR) - 50")
private int birthYear;

しかし、現在の年を取得するコードはかなり醜いですね。ヘルパークラスに入れてみましょう!

public class CalendarHelper {
    public static int todayYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }
}

そして、これを行うことができます:

@SpELAssert(value="#this < #todayYear() - 50", helpers=CalendarHelper.class)
private int birthYear;
于 2014-01-03T23:23:49.170 に答える