开发者

javax.validation to validate list of values?

开发者 https://www.devze.com 2023-02-09 15:31 出处:网络
is there a way to use javax.validation to validate a variable of typ开发者_运维技巧e string called colour that needs to have these values only(red, blue, green, pink) using annotations?

is there a way to use javax.validation to validate a variable of typ开发者_运维技巧e string called colour that needs to have these values only(red, blue, green, pink) using annotations?

i have seen @size(min=1, max=25) and @notnull but is there something like this @In(red, blue, green, pink)

more or less similar to the In-keyword used in mysql


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)


You can create a custom validation annotation. I will write it here (untested code!):

@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
    }

}


you can create an enum

public enum Colors {
    RED, PINK, YELLOW
}

and then in your model, you can validate it like so:

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

which will validate your payload against the enum, given that you have added @Valid in your RestController.


You can create your validation class by your own. for reference https://www.javatpoint.com/spring-mvc-custom-validation

0

精彩评论

暂无评论...
验证码 换一张
取 消