Created
January 31, 2023 09:31
-
-
Save parthdesai1208/c7af9c893cb651d0145910aba0f72e6a to your computer and use it in GitHub Desktop.
custom annotation for validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity(), ConstraintValidatorContext { | |
lateinit var edt: EditText | |
lateinit var btn: Button | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
edt = findViewById(R.id.edt) | |
btn = findViewById(R.id.btn) | |
btn.setOnClickListener { | |
val eighteenOrOlderValidator = EighteenOrOlderValidator() | |
val eighteenOrOlder = EighteenOrOlder() | |
if (eighteenOrOlderValidator.isValid(edt.text.toString(), this)) { | |
Toast.makeText(this, "hurray", Toast.LENGTH_SHORT).show() | |
} else { | |
Toast.makeText(this, eighteenOrOlder.message, Toast.LENGTH_SHORT).show() | |
} | |
} | |
} | |
override fun disableDefaultConstraintViolation() { | |
} | |
override fun getDefaultConstraintMessageTemplate(): String { | |
return "" | |
} | |
override fun buildConstraintViolationWithTemplate(messageTemplate: String?): ConstraintValidatorContext.ConstraintViolationBuilder? { | |
return null | |
} | |
} | |
@Target(AnnotationTarget.FIELD) | |
@Retention(AnnotationRetention.RUNTIME) | |
@Constraint(validatedBy = [EighteenOrOlderValidator::class]) | |
annotation class EighteenOrOlder( | |
val message: String = "validation message here", | |
val group: Array<KClass<*>> = [], | |
val payload: Array<KClass<out Payload>> = [] | |
) | |
class EighteenOrOlderValidator : ConstraintValidator<EighteenOrOlder, String> { | |
override fun isValid(value: String?, context: ConstraintValidatorContext?): Boolean { | |
return value?.length!! >= 5 | |
} | |
override fun initialize(constraintAnnotation: EighteenOrOlder?) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment