I've created a composite annotation that consists of #Digits and #Min
#Digits(integer=12, fraction=0)
#Min(value=0)
#ReportAsSingleViolation
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target( { FIELD, METHOD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Constraint(validatedBy={})
public #interface PositiveInt {
String message() default "{positive.int.msg}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
my problem is, I want to reuse this annotation where I want the #Digits 'integer' value to be specify when the PositiveInteger is use
example
public Demo{
#PositiveInteger(integer=1)
private Integer num1;
#PositiveInteger(integer=2)
private Integer num2;
}
where num1 can be 1-9, and num2 can be 1-99.
Is this even possible, if so, how do I go about this?
Currently, I have to provides a custom ConstraintValidator where i would have my validation code for the #Digits and #Min
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target( { FIELD, ANNOTATION_TYPE, PARAMETER })
#Constraint(validatedBy=PositiveIntConstraintValidator.class)
public #interface PositiveInt {
String message() default "positive.int.msg";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int integer() default 1;
}
public class PositiveIntConstraintValidator implements ConstraintValidator<PositiveInt, Number> {
private int maxDigits;
#Override
public void initialize(PositiveInt constraintAnnotation) {
maxDigits = constraintAnnotation.integer();
if (maxDigits < 1){
throw new IllegalArgumentException("Invalid max size. Max size must be a positive integer greater than 1");
}
}
#Override
public boolean isValid(Number value, ConstraintValidatorContext context) {
if (value == null){
return true;
}
else if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof BigInteger){
String regex = "\\d{"0," + maxDigits + "}";
return Pattern.matches(regex, value.toString());
}
return false;
}
You could make use of #OverridesAnnotation:
#Digits(integer=0, fraction=0)
#Min(value=0)
#ReportAsSingleViolation
#Documented
#Retention(RetentionPolicy.RUNTIME)
#Target( { FIELD, METHOD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Constraint(validatedBy={})
public #interface PositiveInteger {
String message() default "{positive.int.msg}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
#OverridesAttribute(constraint=Digits.class, name="integer")
int digits();
}
That way the value given in #PositiveInteger#digits() will be propagated to #Digits.
Related
Is there a way to pass a variable from a property file to a class annotation?
#MaxPeriod(firstDateField = "startDateFrom", secondDateField = "startDateTo", maxPeriod = "${variable.from.property:31}")
public class ProcessReportFilter {
private LocalDate startDateFrom;
private LocalDate startDateTo;
}
upd: annotation is used in the request object at bean validation
#Target({ElementType.TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = MaxPeriodValidator.class)
#Repeatable(MaxPeriod.List.class)
public #interface MaxPeriod {
String message() default "Period between {firstDateField} and {secondDateField} must not exceed {maxPeriod} day(-s)";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String firstDateField();
String secondDateField();
long maxPeriod();
#Target({ElementType.TYPE})
#Retention(RUNTIME)
#interface List {
MaxPeriod[] value();
}
}
I created a custom validator in Spring Boot but when I pass the #PathVariable value to the validator, it gets the parameter name for null values.
#Validated // added for controller
#GetMapping("/employees/{code}")
public ResponseEntity<ApiResponse<List<RunwayBean>>> findByCode(
#ValidInput #PathVariable("code") String code) {
// ...
}
#Documented
#Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE})
#Retention(RUNTIME)
#Constraint(validatedBy = {InputValidator.class})
public #interface ValidInput {
String message() default INVALID_INPUT;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And then in the validator below, str value is :code when I pass the parameter null on Postman. But when I add any string, it can be received correctly. So, how can I fix it?
public class InputValidator implements ConstraintValidator<ValidInput, String> {
#Override
public void initialize(ValidInput constraintAnnotation) {}
#Override
public boolean isValid(String str, ConstraintValidatorContext context) {
return str!= null && !str.isBlank();
// str = ":code" when #PathVariable value is null
}
}
I need to return to API client list of valid DecisionStates when the client passes invalid string that cannot be mapped to DecisionStates enum.
Annotataion definition:
#Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = ValueOfEnumValidator.class)
public #interface ValueOfEnum {
Class<? extends Enum<?>> enumClass();
String message() default "must be any of enum {enumClass}: [" + Arrays.toString(enumClass().getEnumConstants()).replaceAll("^.|.$", "") + "]"; // <-- not compiling
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
DTO:
#ValueOfEnum(enumClass = DecisionState.class)
String state;
ConstraintValidator implementation:
public class ValueOfEnumValidator implements ConstraintValidator<ValueOfEnum, CharSequence> {
private List<String> acceptedValues;
#Override
public void initialize(ValueOfEnum annotation) {
acceptedValues = Stream.of(annotation.enumClass().getEnumConstants())
.map(Enum::name)
.collect(Collectors.toList());
}
#Override
public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return acceptedValues.contains(value.toString());
}
}
Is there are any java annotation(s) that can validate like the example below?
String test;
test = null; //valid
test = ""; //invalid
test = " "; //invalid
test = "Some values"; //valid
You need to create a custom annotation: #NullOrNotBlank
First create the custom annotation: NullOrNotBlank.java
#Target( {ElementType.FIELD})
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = NullOrNotBlankValidator.class)
public #interface NullOrNotBlank {
String message() default "{javax.validation.constraints.NullOrNotBlank.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default {};
}
Then the actual validator: NullOrNotBlankValidator.java
public class NullOrNotBlankValidator implements ConstraintValidator<NullOrNotBlank, String> {
public void initialize(NullOrNotBlank parameters) {
// Nothing to do here
}
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
return value == null || value.trim().length() > 0;
}
}
There isn't such an annotation in either javax.validation or Hibernate Validator. There was a request to add one to Hibernate Validator but it was closed as "won't fix" due to the possibility of writing your own relatively easily. The suggest solution was to either use your own annotation type defined like this:
#ConstraintComposition(OR)
#Null
#NotBlank
#ReportAsSingleViolation
#Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Retention(RUNTIME)
#Constraint(validatedBy = { })
public #interface NullOrNotBlank {
String message() default "{org.hibernate.validator.constraints.NullOrNotBlank.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
or to use the #Pattern annotation with a regular expression that requires a non-whitespace character to be present (as the Pattern annotation accepts nulls and does not match them against the pattern).
Where is a nice javax.validation.constraints.Pattern annotation.
You can annotate the field with:
#Pattern(regexp = "^(?!\\s*$).+", message = "must not be blank")
This checks if field matches regex. The regex itself is something but not blank (see details here). It uses negative lookahead.
This is possible without creating a custom annotation, by using javax.validation.constraints.Size
// Null values are considered valid
#Size(min=1) String test;
The best way is to create your own constraint validator,
//custom annotation
#Documented
#Constraint(validatedBy = CustomCheck.class)
#Target( { ElementType.METHOD, ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
public #interface CustomConstarint {
String message() default "Invalid data";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
//validation logic goes here
public class CustomCheck implements
ConstraintValidator<CustomConstarint, String> {
#Override
public void initialize(CustomConstarint customConstarint) {
}
#Override
public boolean isValid(String field,
ConstraintValidatorContext cxt) {
//write your logic to validate the field
}
}
Did you try Hibernate-Validator? I think that's what you are looking for.
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
public class MyModel {
#NotNull
private String str1;
#NotEmpty
private String str2;
#NotBlank
private String str3;
}
I wrote a custom annotation in my project called CGC:
#Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = CGCValidator.class)
public #interface CGC {
String message() default "{person.cgc.error}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
boolean canBeNull() default false;
#Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
#Retention(RUNTIME)
#Documented
public #interface List {
CGC[] value();
}
}
I have a validator class that uses the annotation and basically, as my first validation I wanna check if the field is null, but only If the annotation for that field has specified the "canBeNull" element as true (#CGC(canBeNull="true")). My question is: how can I access the canBeNull element inside my validator class?
*The validator should be something like this:
public class CGCValidator implements ConstraintValidator<CGC, String> {
#Override
public void initialize(CGC annotation) {
}
#Override
public boolean isValid(String cgc, ConstraintValidatorContext constraintValidatorContext) {
if(!canBeNull() && cgc == null) {
return false;
}
...
You can capture the canBeNull value in the initialize function:
class CGCValidator implements ConstraintValidator<CGC, String> {
boolean canBeNull;
#Override
public void initialize(CGC constraintAnnotation) {
canBeNull = constraintAnnotation.canBeNull();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return canBeNull || value != null;
}
}