Alfredo Morales
Alfredo Morales

Reputation: 93

Annotation for validation base64 string in Spring

I have a rest service with my request body bean annotated with javax.validation like @NotBlank @NotNull @Pattern etc., and in one specific field I receive a file encoded as a string base64,

so, is there an annotation, or how could I write a custom validation annotation, so it would check if the string is really a base64 string?

I just need a validation like this in annotation form:

try {
    Base64.getDecoder().decode(someString);
    return true;
} catch(IllegalArgumentException iae) {
    return false;
}

thnx in advance

Upvotes: 3

Views: 1979

Answers (1)

kerbermeister
kerbermeister

Reputation: 4221

Yes, you could write your own annotations and validators for them.

Your annotation would look like this:

@Documented
@Constraint(validatedBy = Base64Validator.class)
@Target( { ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface IsBase64 {
    String message() default "The string is not base64 string";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Constraint validator javax.validation implementation (I'm using here your code for the actual validation):

public class Base64Validator implements ConstraintValidator<IsBase64, String> {
    
    @Override
    public boolean isValid(String value, ConstraintValidatorContext cxt) {
        try {
            Base64.getDecoder().decode(value);
            return true;
        } catch(IllegalArgumentException iae) {
            return false;
        }
    }
}

Example data class with the annotated field:

@Data
public class MyPayload {
    @IsBase64
    private String value;
}

And controller method example with @Valid annotation which is required:

@PostMapping
public String test(@Valid @RequestBody MyPayload myPayload) {
    return "ok";
}

UPDATED: Also, if you want to check whether the fiven string is a base64 string, you can use the method isBase64() from apache-commons libraby, the class is org.apache.commons.codec.binary.Base64 So, it would look like this Base64.isBase64(str);

Upvotes: 8

Related Questions