Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

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

    }

}
question from:https://stackoverflow.com/questions/65641875/jetpack-compose-textfield-inputfilter-to-have-only-currency-regex-inputs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...