2
0

More than 1 year has passed since last update.

TextFieldで数字,英語,記号だけを入力させたい時

Last updated at Posted at 2022-05-26

内容

アカウント登録などのフォームを制作する際に、メールアドレス、パスワードなどの
TextFieldに、入力できる値を制限したい場面を想定しています。

方法

数字のみ

数字のみはinputFormattersで用意されていて、以下の記述を足すことで簡単に設定ができます。

TextField(
    keyboardType: TextInputType.number,
    inputFormatters: [FilteringTextInputFormatter.digitsOnly]
)

英字,記号など

FilteringTextInputFormatter.allow() : 一致するものを許可
FilteringTextInputFormatter.deny() : 一致しないものを許可

inputFormatters: [
    FilteringTextInputFormatter.allow(
    RegExp(r'[a-zA-Z0-9@_-.]')),
],

FilteringTextInputFormatter.allow()で正規表現を利用します。
以下では数字、小文字,大文字の英数
アットマーク、アンダーバー、ハイフン、ピリオドを対応させています。
繋げて書いて反映されるので空白カンマなどの区切りを間違えて入れないようにしましょう。

Dartにおける正規表現の詳細はこちら ↓
Flutterで正規表現を用いたemailのvalidationを実装

任意の処理を持たせたい時

一致しない入力にエラーを表示させたい場合などはTextInputFormatter.withFunction
用いることで任意の処理を持たせることができます。

TextInputFormatter.withFunction((oldValue, newValue) =>
 RegExp(r^[a-zA-Z09]+).hasMatch(newValue.text) ? newValue : oldValue)

参考リンク

TextFieldで入力文字を制限したい

2
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
2
0