All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.icerockdev.validation.DateFormat.kt Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
/*
 * Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
 */

package com.icerockdev.validation

import org.joda.time.format.DateTimeFormat
import javax.validation.Constraint
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
import javax.validation.Payload
import kotlin.reflect.KClass

/**
 * Validation annotation to validate date field that 2 fields has match pattern.
 *
 * Example, compare date by format:
 * @DateFormat(pattern = "dd-MM-yyyy")
 */
@Target(AnnotationTarget.FIELD)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@Constraint(validatedBy = [DateFormatValidator::class])
@MustBeDocumented
annotation class DateFormat(
    val message: String = "{message.key}",
    val groups: Array> = [],
    val payload: Array> = [],
    val pattern: String
)

class DateFormatValidator : ConstraintValidator {
    private lateinit var pattern: String
    override fun initialize(constraintAnnotation: DateFormat) {
        pattern = constraintAnnotation.pattern
    }

    override fun isValid(value: String?, constraintContext: ConstraintValidatorContext?): Boolean {
        return if (value == null) {
            true
        } else try {
            DateTimeFormat.forPattern(pattern).parseDateTime(value)
            true
        } catch (e: IllegalArgumentException) {
            false
        }
    }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy