39

有没有办法使用 javax.validation 来验证一个名为 color 的字符串类型变量,该变量需要使用注释仅具有这些值(红色、蓝色、绿色、粉红色)?

我见过 @size(min=1, max=25)@notnull但是有没有这样的东西@In(red, blue, green, pink)

或多或少In-keyword类似于mysql

4

4 回答 4

107

In that case I think it would be simpler to use the @Pattern annotation, like the snippet below. If you want a case insensitive evaluation, just add the appropriate flag:

@Pattern(regexp = "red|blue|green|pink", flags = Pattern.Flag.CASE_INSENSITIVE)

于 2013-01-24T12:55:02.960 回答
12

您可以创建自定义验证注释。我会写在这里(未经测试的代码!):

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = InConstraintValidator.class)
public @interface In
{
    String message() default "YOURPACKAGE.In.message}";

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

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

    Object[] values(); // TODO not sure if this is possible, might be restricted to String[]
}

public class InConstraintValidator implements ConstraintValidator<In, String>
{

    private Object[] values;

    public final void initialize(final In annotation)
    {
        values = annotation.values();
    }

    public final boolean isValid(final String value, final ConstraintValidatorContext context)
    {
        if (value == null)
        {
            return true;
        }
        return ...; // check if value is in this.values
    }

}
于 2011-03-03T09:50:02.117 回答
3

你可以创建一个枚举

public enum Colors {
    RED, PINK, YELLOW
}

然后在您的模型中,您可以像这样验证它:

public class Model {
    @Enumerated(EnumType.STRING)
    private Colors color;
}

假设您在 RestController 中添加了@Valid,它将根据枚举验证您的有效负载。

于 2017-10-16T11:34:49.803 回答
1

您可以自己创建验证类。供参考https://www.javatpoint.com/spring-mvc-custom-validation

于 2021-04-30T10:48:03.043 回答