📩

【Flutter】TextFormField でメールアドレスのバリデーションを行う

2021/06/30に公開

email_validator を使います。

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  # 追加
  email_validator: ^2.0.1

実装例

保存ボタンをクリックしたときに、入力値が不正ならエラーメッセージを表示するサンプルを実装してみたいと思います。

main.dart

import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Email Validation Sample',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<FormState> _key = GlobalKey<FormState>();

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Email Validation Sample'),
        actions: [
          IconButton(
            icon: Icon(Icons.save),
            onPressed: () {
              if (!_key.currentState!.validate()) return;
	      _key.currentState!.save();
            },
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(10.0),
        child: Center(
          child: Form(
            key: _key,
            child: TextFormField(
              decoration: InputDecoration(
                labelText: 'Email',
              ),
              validator: (value) {
                if ((value == null) || !EmailValidator.validate(value)) {
                  return 'Emailが不正です';
                }
              },
              onSaved: (value) => null,
            ),
          ),
        ),
      ),
    );
  }
}

Discussion