Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpackandroid-compose-textfield

Restrict only numbers, commas(,) or only one dot(.) using Regex for TextField Jetpack compose


I am working on customizing TextField in Jetpack Compose, I want restrict the input from the user to numbers, commas or a single dot.

The regular expression that I am currently using is val expression = Regex("[\\d,.]+") . It works fine for numbers and commas but I am able to enter multiple dots(.) which I don't want. I want one single dot only. Here is my Jetpack Compose code.

    val expression = Regex("[\\d,.]+")

    val keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Number,
        imeAction = ImeAction.Done
    )

    TextField(
        value = text,
        onValueChange = {
            if (it.isEmpty() || it.matches(expression))
               onValueChange(it)
        },
        keyboardOptions = keyboardOptions,
        keyboardActions = KeyboardActions(
            onDone = {  }
        ),
    )

Solution

  • Actually you are accepting only numbers using keyboard options and that's why you don't need to validate digits in regex... but for the question you have asked you can use this regex:

    val expression = Regex("[\\d,]*[.]?[\\d,]*"
    
    • Question Mark(?) is for zero or one occurrence
    • Asterisk(*) is for zero or more occurrences
    • Plus(+) is for one or more occurrences

    NOTE: This will accept dot(.) and comma(,) as first and last character as well.

    And you also don't need to validate it.isEmpty() in onValueChange lambda because it will also handled using the regex as it also accepts empty strings.