HackToTech

Hack To Technology

ConstraintValidatorのisValidでエラーメッセージを変更する

isValid 内でValidationMessagseのキー指定して切り替えって出来るんだっけ?ってなったので、個人的なメモ書き

ドキュメントを読んでいたら出来そうだったので試した
あんまり使う機会はなさそうではある(基本的にはConstraintsは分けるし、相関チェックみたいなパターンぐらいの認識)

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [CustomConstraints.CustomConstraintValidator::class])
annotation class CustomConstraints(
    val message: String = "{com.example.customconstraintssample.constraints.CustomConstraints.message}",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
) {
    class CustomConstraintValidator : ConstraintValidator<CustomConstraints, IndexRequest> {
        override fun isValid(value: IndexRequest, context: ConstraintValidatorContext): Boolean {
            return when (value.type) {
                IndexType.TYPE1 -> {
                    if (value.type1Value != null && value.type2Value == null) return true
                    context.disableDefaultConstraintViolation()
                    context.buildConstraintViolationWithTemplate("{com.example.customconstraintssample.constraints.CustomConstraints.type1.message}")
                        .addConstraintViolation()
                    false
                }
                IndexType.TYPE2 -> {
                    if (value.type1Value == null && value.type2Value != null) return true
                    context.disableDefaultConstraintViolation()
                    context.buildConstraintViolationWithTemplate("{com.example.customconstraintssample.constraints.CustomConstraints.type2.message}")
                        .addConstraintViolation()
                    false
                }
            }
        }
    }
}

使う側

enum class IndexType {
    TYPE1,
    TYPE2,
}

@CustomConstraints
data class IndexRequest(
    val type: IndexType,
    val type1Value: String?,
    val type2Value: Int?,
)

試したソースはここ github.com