Skip to content

Instantly share code, notes, and snippets.

@parthdesai1208
Created January 31, 2023 09:31
Show Gist options
  • Save parthdesai1208/c7af9c893cb651d0145910aba0f72e6a to your computer and use it in GitHub Desktop.
Save parthdesai1208/c7af9c893cb651d0145910aba0f72e6a to your computer and use it in GitHub Desktop.
custom annotation for validation
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