Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create custom validator with parameters in spring boot?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading