when validating a controller using kotlin/spring, ...
# spring
x
when validating a controller using kotlin/spring, how would you validate that a date is after the other? I tried creating a data class and having an
Copy code
@AssertTrue
in the data class, but I'm getting an unused function error (🧵 )
example:
Copy code
@GetMapping("/test")
fun validTest(@PathVariable params: Params){
  foo(params.from, <http://params.to|params.to>)
}

data class Params(val from: Instant, val to: Instant){
  @AssertTrue("from should be before to")
  fun areDatesValid(): Boolean {
    return from.isBefore(to)
  }
}
(id rather not create a new annotation for this)
j
Why are you getting an unused function error on a public function? Does the error go away if you use it in a unit test?
x
yes
t
You were super close. The issue is that your @AssertTrue annotation was not on a function that conforms to the JavaBean spec (boolean accessors are expects to start with
is
or
get
) I’d also mark your parameter object as @Valid, so validation is applied. You probably already have it, but you also need this dependency to get all the validation goodness:
Copy code
implementation("org.springframework.boot:spring-boot-starter-validation")
j
The issue is that your @AssertTrue annotation was not on a function that conforms to the JavaBean spec
This doesn't sound right. See https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#chapter-method-constraints
t
@Jacob I agree that this is a bit confusing, per that documentation I’d expect to be able to validate any arbitrarily named method. I don’t have time to dig into the root cause of this behavior, but I did create a project that demonstrates the name change exhibiting the behavior the OP desired. Here is the test that shows that naming was the culprit in this case: https://github.com/tomhermann/spring-validation-example/blob/main/src/test/kotlin/com/zombietank/validation/MethodConstraintControllerTest.kt
128 Views