1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ComposeのTextFieldで入力制限を実装する(テンプレート)

1
Posted at

TextFieldの基本

var text by remember { mutableStateOf("") }

TextField(
    value = text,
    onValueChange = { text = it }
)

このonValueChangeの中で制限を追加していきます

文字数制限

TextField(
    value = text,
    onValueChange = {
        if (it.length <= 10) {
            text = it
        }
    },
    label = { Text("10文字まで") }
)
  • 入力された値をそのまま代入しない
  • 条件を満たしたときだけ state を更新する

数値のみ入力

TextField(
    value = text,
    onValueChange = {
        if (it.all { char -> char.isDigit() }) {
            text = it
        }
    },
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Number
    )
)
  • KeyboardType.Number はキーボード表示を変えるだけ
  • 入力値の制限は別途必要

文字数 + 数値制限

TextField(
    value = text,
    onValueChange = {
        if (it.length <= 6 && it.all { char -> char.isDigit() }) {
            text = it
        }
    }
)
  • 郵便番号、年齢、ID入力などに使える

空白禁止

TextField(
    value = text,
    onValueChange = {
        text = it.filterNot { char -> char.isWhitespace() }
    }
)
  • singleLine = true を指定する
  • コピペで改行が入る可能性も考える

小数点を許容

val regex = Regex("^\d*(\.\d*)?$")

TextField(
    value = text,
    onValueChange = {
        if (regex.matches(it)) {
            text = it
        }
    },
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Decimal
    )
)
  • . を1つだけ許可する

電話番号っぽい整形

TextField(
    value = phoneNumber,
    onValueChange = {
        phoneNumber = formatPhoneNumber(it)
    },
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Phone
    )
)
  • keyboardOptionsを指定してそれっぽくできる
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?