📩

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

2 min read

email_validatorを使います。

pubspec.yamlにemail_validatorを追加する

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

  # 追加
  email_validator: ^2.0.1

保存ボタンをクリックして、入力値が不正ならエラーメッセージを表示する

以下、全体の実装です。

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

ログインするとコメントできます