Home > Software design >  kotlin regex pattern for valid amount
kotlin regex pattern for valid amount

Time:08-18

I want to restrict Field to take only valid amounts, I have already enabled the number keyboard but It contains some symbols like - (- , SPACE)

Example Valid Amount: 200, 200.00

CodePudding user response:

You can use a regex to check if input can be parse as Double.. Somthing like this ->

@Composable
fun AmountTextField(
text: String,
onChanged: (String) -> Unit) {
TextField(value = text,
    onValueChange = {
        if (it.isEmpty() || it.matches("[0-9]{1,13}(\\.[0-9]*)?".toRegex())) onChanged(it)
    },
    keyboardOptions =
    KeyboardOptions.Default.copy(keyboardType = KeyboardType.Decimal)
)
}

Alternatively you can also use toDoubleOrNull .

@Composable
fun AmountTextField(
text: String,
onChanged: (String) -> Unit) {
TextField(value = text,
    onValueChange = {
        if (it.isEmpty() || it.toDoubleOrNull()!=null) onChanged(it)
    },
    keyboardOptions =
    KeyboardOptions.Default.copy(keyboardType = KeyboardType.Decimal)
)
}

CodePudding user response:

If I understood that correctly, you should use [0-9] (\.[0-9] )?$ so that you can do [some numbers without separation] and a dot plus some more numbers without separation, both of the latter as optionals.

  • Related