Home > Back-end >  How to create custom validator with parameters in spring boot?
How to create custom validator with parameters in spring boot?

Time:07-21

I have written a validator for cron string that checks for a minimal interval.

@Constraint(validatedBy = [ValidMinimalInterval.JsonStringValidator::class])
@Target(AnnotationTarget.FIELD, AnnotationTarget.CLASS, AnnotationTarget.PROPERTY_GETTER)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
annotation class ValidMinimalInterval(
    val message: String = "The cron string doesn't fit in the minimal interval of 60 minutes",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
) {
    class JsonStringValidator :
        ConstraintValidator<ValidMinimalInterval?, String?> {
        override fun initialize(jsonString: ValidMinimalInterval?) {}
        override fun isValid(string: String?, context: ConstraintValidatorContext): Boolean {
            return string?.let {
                val min = 1000 * 3600
                val cron = CronExpression(string)
                val execDate = cron.getNextValidTimeAfter(Date())
                val nextExecDate = cron.getNextValidTimeAfter(execDate)
                val diff = nextExecDate.time - execDate.time
                diff >= min
            } ?: true
        }
    }
}

This works fine, but I want the validator to take in the parameter for minimal interval like @ValidMinimalInterval(min = 1000 * 3600). How can I achieve that?

CodePudding user response:

You just add it as an annotation property

annotation class ValidMinimalInterval(
    val message: String = "The cron string doesn't fit in the minimal interval of 60 minutes",
    val groups: Array<KClass<*>> = [],
    val payload: Array<KClass<out Payload>> = []
    val min: Integer //or whatever it is in Kotlin
    
)
  • Related