0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-06-30

email_validatorを使います。

pubspec.yamlにemail_validatorを追加する

pubspec.yaml
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 {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Email Validation Sample',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

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

  @override
  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,
            ),
          ),
        ),
      ),
    );
  }
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?