Flutter フォームと検証

この節では、Flutterでのフォームの作成、検証、送信処理について説明します。


TextFormField - フォーム入力

TextFormFieldはフォーム専用のTextFieldで、組み込みの検証機能をサポートしています。

例:基本フォーム

class LoginForm extends StatefulWidget {
  const LoginForm({super.key});

  @override
  State<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  // フォームキー(検証用)
  final _formKey = GlobalKey<FormState>();

  // 入力コントローラー
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          // ユーザー名入力
          TextFormField(
            controller: _usernameController,
            decoration: const InputDecoration(
              labelText: 'ユーザー名',
              prefixIcon: Icon(Icons.person),
            ),
            // バリデータ
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'ユーザー名を入力してください';
              }
              if (value.length < 3) {
                return 'ユーザー名は3文字以上必要です';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          // パスワード入力
          TextFormField(
            controller: _passwordController,
            obscureText: true,  // パスワードを隠す
            decoration: const InputDecoration(
              labelText: 'パスワード',
              prefixIcon: Icon(Icons.lock),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'パスワードを入力してください';
              }
              if (value.length < 6) {
                return 'パスワードは6文字以上必要です';
              }
              return null;
            },
          ),
          const SizedBox(height: 24),
          // 送信ボタン
          ElevatedButton(
            onPressed: _submit,
            child: const Text('ログイン'),
          ),
        ],
      ),
    );
  }

  void _submit() {
    // フォームを検証
    if (_formKey.currentState?.validate() ?? false) {
      // 検証成功
      print('ユーザー名: ${_usernameController.text}');
      print('パスワード: ${_passwordController.text}');
      // サーバーに送信...
    } else {
      // 検証失敗
      print('フォーム検証に失敗しました');
    }
  }
}

よく使うバリデータ

例:よく使う検証ルール

// ユーザー名の検証
String? validateUsername(String? value) {
  if (value == null || value.isEmpty) {
    return 'ユーザー名を入力してください';
  }
  if (!RegExp(r'^[a-zA-Z0-9_]+$').hasMatch(value)) {
    return '英数字とアンダースコアのみ使用できます';
  }
  return null;
}

// メールアドレスの検証
String? validateEmail(String? value) {
  if (value == null || value.isEmpty) {
    return 'メールアドレスを入力してください';
  }
  final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
  if (!emailRegex.hasMatch(value)) {
    return '有効なメールアドレスを入力してください';
  }
  return null;
}

// パスワード強度の検証
String? validatePassword(String? value) {
  if (value == null || value.isEmpty) {
    return 'パスワードを入力してください';
  }
  if (value.length < 8) {
    return 'パスワードは8文字以上必要です';
  }
  if (!RegExp(r'[A-Z]').hasMatch(value)) {
    return 'パスワードには少なくとも1つの大文字が含まれている必要があります';
  }
  if (!RegExp(r'[0-9]').hasMatch(value)) {
    return 'パスワードには少なくとも1つの数字が含まれている必要があります';
  }
  return null;
}

// 携帯電話番号の検証
String? validatePhone(String? value) {
  if (value == null || value.isEmpty) {
    return '携帯電話番号を入力してください';
  }
  final phoneRegex = RegExp(r'^1[3-9]\d{9}$');
  if (!phoneRegex.hasMatch(value)) {
    return '有効な携帯電話番号を入力してください';
  }
  return null;
}

// パスワードの一致確認の検証
String? validateConfirmPassword(String? value, String password) {
  if (value == null || value.isEmpty) {
    return 'パスワードを確認してください';
  }
  if (value != password) {
    return 'パスワードが一致しません';
  }
  return null;
}

複雑なフォームの例

例:登録フォーム

class RegisterForm extends StatefulWidget {
  const RegisterForm({super.key});

  @override
  State<RegisterForm> createState() => _RegisterFormState();
}

class _RegisterFormState extends State<RegisterForm> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _emailController = TextEditingController();
  final _phoneController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();

  bool _acceptTerms = false;

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // ユーザー名
          TextFormField(
            controller: _usernameController,
            decoration: const InputDecoration(labelText: 'ユーザー名'),
            validator: validateUsername,
          ),
          const SizedBox(height: 16),
          // メールアドレス
          TextFormField(
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            decoration: const InputDecoration(labelText: 'メールアドレス'),
            validator: validateEmail,
          ),
          const SizedBox(height: 16),
          // 携帯電話番号
          TextFormField(
            controller: _phoneController,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(labelText: '携帯電話番号'),
            validator: validatePhone,
          ),
          const SizedBox(height: 16),
          // パスワード
          TextFormField(
            controller: _passwordController,
            obscureText: true,
            decoration: const InputDecoration(labelText: 'パスワード'),
            validator: validatePassword,
          ),
          const SizedBox(height: 16),
          // パスワードの確認
          TextFormField(
            controller: _confirmPasswordController,
            obscureText: true,
            decoration: const InputDecoration(labelText: 'パスワードの確認'),
            validator: (value) => validateConfirmPassword(
              value,
              _passwordController.text,
            ),
          ),
          const SizedBox(height: 16),
          // 規約に同意
          CheckboxListTile(
            value: _acceptTerms,
            onChanged: (value) {
              setState(() {
                _acceptTerms = value ?? false;
              });
            },
            title: const Text('利用規約に同意します'),
            controlAffinity: ListTileControlAffinity.leading,
          ),
          const SizedBox(height: 24),
          // 送信ボタン
          ElevatedButton(
            onPressed: _acceptTerms ? _submit : null,
            child: const Text('登録'),
          ),
        ],
      ),
    );
  }

  void _submit() {
    if (_formKey.currentState?.validate() ?? false) {
      // フォームを送信
      print('登録が完了しました!');
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }
}

フォーム検証は、クライアント側(ユーザー体験)とサーバー側(セキュリティ)の両方で行うべきであり、クライアント側の検証だけに依存してはいけません。

その他の拡張