0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

jakarta.validationでカスタムアノテーションを作ってみる

Posted at

jakarta.validationを使った簡単なバリデーションのアノテーションを作ってみます。

まずはアノテーションを作ります。
これ @Constraint(validatedBy = NameValidator.class) が肝で、NameValidatortというクラス内でバリデーションのチェックをします。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NameValidator.class)
public @interface ValidateName {
    String message() default "Invalid name: must start with uppercase";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

isValid関数内で値のチェックを行います。

public class NameValidator implements ConstraintValidator<ValidateName, String> {
    @Override
    public void initialize(ValidateName constraintAnnotation) {}

    @Override
    public boolean isValid(String name, ConstraintValidatorContext context) {
        return  name.matches("^[A-Z]");
    }
}

コントローラーなどを書いて実行してみます。
できたもの
https://github.com/pbogawa/sampleValidate

ポストマンから呼び出してみました。
正常系
image.png

異常系
勝手に400番エラーにしてくれるみたいです。
image.png

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?