Search code examples
kotlinandroid-jetpack-composeandroid-jetpack

Regex for TextField is not working as expected in kotlin?


I require certain constraints in my project, particularly within the regex, to restrict user input and format it appropriately. These rules are intended for implementation within the TextField component in my Jetpack Compose project.

Rules:

  • Zero and Dot cannot be at the start.
  • There can only be one dot.
  • After the dot, there can only be two digits, and before the dot, there can only be four digits.
  • If the user does not enter a dot, they can only input four digits. If they do enter a dot, they can add two digits after it.

Examples: (These examples are provided for reference purposes only.)

  • 8956.32 -> Valid
  • 45 -> Valid
  • 562.2 -> Valid
  • 0655 -> Invalid
  • 0356.00 -> Invalid
  • .003 -> Invalid

I tried belwo code but this is not working as expected.

var text by remember { mutableStateOf("") }
val regex = remember { Regex("^(?!0|\\.)(?!.*\\.\\.)\\d{1,4}(\\.\\d{1,2})?$") }

TextField(
                label = R.string.label_days,
                value = text,
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Number
                ),
                onValueChange = { days ->
                    if (days.isEmpty() || regex.matches(days)){
                     text = days
                    }
                })

Solution

  • Below code will work for your requirement

        var text by remember { mutableStateOf("") }
        val regex = remember { Regex("^(?!0)(?!.*\\.\\..*|\\.$)\\d{0,4}(\\.\\d{0,2})?\$") }
        TextField(
            label = {
                Text(text = "Days")
            },
            value = text,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number
            ),
            onValueChange = { days ->
                if (days.isEmpty() || days.matches(regex)) {
                    text = days
                }
            }
        )