PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How to create custom validator with parameters in spring boot?

 July 30, 2022     java, kotlin, spring, spring-boot, validation     No comments   

Issue

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?


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
    
)


Answered By - Antoniossss
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing