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
list = new ArrayList<E>(); } public ValidList(List<E> list) { this. list = list; } // Bean-like methods, used by javax. validation but ignored by JSON parsing public List<E> getList() { return list; } public void setList(List<E> list) { this.
While it's not widely known, Java Bean Validation ships with the validateProperty() and validateValue() methods, which can be used for validating the individual fields of a constrained class as well as values even before assigning them.
You don't have to use any wrapper class just to validate a list of strings. Just use @EachPattern constraint from validator-collection: @NotNull @EachPattern(regexp="\b[A-Z0-9. _%+-]+@[A-Z0-9.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With