59

is there a way to use javax.validation to validate a variable of type 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

1
  • Hi. i am guessing this is not possible using javax validators then? i suppose i can just create a constraint on the table/database level? Commented Feb 8, 2011 at 9:50

4 Answers 4

135

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)

Sign up to request clarification or add additional context in comments.

3 Comments

what if the red blue etc are a constant?
does it allow also empty values ?
@user666 did you get a solution to use Pattern annotation for using constants in the regexp? e.g. AppConstants.RED, AppConstants.BLUE etc
12

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
    }

}

1 Comment

Useful when trying to validate list of char, but you can't define 'values' as an array of objects. Compiler gives this error: 'Invalid type Object[] for the annotation attribute In.values; only primitive type, String, Class, annotation, enumeration are permitted or 1-dimensional arrays thereof'
3

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.

2 Comments

I don't think so. @Enumerated is a javax.persistence annotation, not a javax.validation annotation.
ccleve is correct, but worth noting that using an enum type can inherently enforce a limited list of values as long as your deserializer, marshaller, or other code does not fall back to null (though @NotNull could solve that). The issue is that it will likely throw some kind of deserialization error, and not be grouped with and handled the same way as the other validations.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.