Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose TextField InputFilter to have only currency Regex inputs

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

    }

}
like image 893
Thracian Avatar asked Oct 28 '25 03:10

Thracian


1 Answers

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")
}
like image 60
nglauber Avatar answered Oct 30 '25 06:10

nglauber