Skip to content

Kotlin request dto validation with annotations

Elena edited this page Aug 13, 2021 · 12 revisions

instead of Java version @NotNull Integer someInt;

1. Validation fields with type Int/Long:

Kotlin data class and Bean validation: @NotNull on Long/Int fields does not work as predict. (as described here https://stackoverflow.com/questions/49896933/kotlin-data-class-and-bean-validation-notnull-on-long-fields-does-not-work)

so we use instead of

@field:NotNull
val bornYear: Int,

this variant:

@field:NotNull
val bornYear: Int?,

By making the field nullable, you're allowing it to be constructed, so that the JSR 303 validation can run on the object. As validator doesn't run until the object is constructed.

2. Validation fields with type String use template like:

@field:NotEmpty(message = "{validation.field.fullName.empty}")
val name: String

@field:NotBlank(message = "{validation.field.email.blank}")
@field:Email(message = "{validation.field.email.invalid-format}")
@field:Pattern(
    regexp = VALID_EMAIL_ADDRESS_REGEX_WITH_EMPTY_SPACES_ACCEPTANCE,
    message = "{validation.field.email.invalid-format.cyrillic.not.allowed}"
)
val email: String,

@field:NotBlank(message = "{validation.field.password.blank}")
@field:Size(min = 4, max = 20, message = "{validation.field.password.invalid-format}")
var password: String,

3. Validation fields with Time/Date types works correct, like

@field:NotNull
var startTime: LocalDateTime,