Validate UUID Restful service

≡放荡痞女 提交于 2021-02-08 20:54:09

问题


I have a RESTful service which receives POST request with UUID values and writes them in DB. So the problem is to validate if UUID is valid or not. For this purpose I implemented custom annotation:

@Constraint(validatedBy = {})
@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Pattern(regexp = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}")
public @interface validUuid {

    String message() default "{invalid.uuid}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

But for some reason it doesn't work, even if I pass valid UUID I constantly get an exception:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.util.UUID'

Are there any options to validate UUID properly?


回答1:


You cannot apply the @Pattern annotation to something (java.util.UUID) that is not a CharSequence. From the @Pattern annotation documentation (emphesizes mine):

Accepts CharSequence. null elements are considered valid.

Moreover, as far as I see you try to extend the behavior of the validation annotation handler by passing it to the new annotation definition.

If you wish to perform more complex validation, simply create your annotation without another validation annotations - their combining doesn't work like this. There must be something to recognize annotations and validate them.

@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = UuidValidator.class)
public @interface ValidUuid {

    String message() default "{invalid.uuid}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Now, create a validator which implements ConstraintValidator<ValidUuid, UUID> and override the methods performing the validation itself.

public class UuidValidator implements ConstraintValidator<ValidUuid, UUID> {
    private final String regex = "....." // the regex

    @Override
    public void initialize(ValidUuid validUuid) { }

    @Override
    public boolean isValid(UUID uuid, ConstraintValidatorContext cxt) {
        return uuid.toString().matches(this.regex);
    }
}

And apply the annotation:

@ValidUuid
private UUID uuId;



回答2:


you can use UUID.fromString(...); and catch IllegalArgumentException



来源:https://stackoverflow.com/questions/53868539/validate-uuid-restful-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!