3

Is it possible to have list of InputFilters for example only letting inputs such as $1,01 or $100,95 that was done with

editText.filters = arrayOf(CurrencyFormatInputFilter(), InputFilter.LengthFilter(8))

class CurrencyFormatInputFilter : InputFilter {

    private val pattern = Pattern.compile(CURRENCY_INPUT_REGEX)

    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence? {

        val result = (dest.subSequence(0, dstart).toString()
                + source.toString()
                + dest.subSequence(dend, dest.length))

        val matcher = pattern.matcher(result)

        return if (!matcher.matches()) dest.subSequence(dstart, dend) else null

    }

}
Thracian
  • 43,021
  • 16
  • 133
  • 222

1 Answers1

6

My suggestion would be display an error while the value inserted is invalid. For instance:

fun isValidEmail(emailStr: String?) = 
    Pattern
        .compile(
            "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", 
            Pattern.CASE_INSENSITIVE
        ).matcher(emailStr).find()

...

var emailText by remember { mutableStateOf("") }
var showError by remember { mutableStateOf(false) }
TextField(
    value = emailText,
    onValueChange = {
        emailText = it
        showError = !isValidEmail(it)
    },
    isErrorValue = showError,
    label = { Text(text = "Email") },
    modifier = Modifier.fillMaxWidth()
)
if (showError) {
    Text("Email is invalid")
}
nglauber
  • 18,674
  • 6
  • 70
  • 75