首页 > 解决方案 > 如何验证电子邮件或电话或 Null 的颤动文本字段?

问题描述

如何验证电子邮件或电话的相同字段或不为空?

TextFormField(
                        
                        // validator: ???,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.all(16.0),
                          hintText: "hint_phone_no_email_address",
                          filled: true,
                          fillColor: Colors.grey.withOpacity(0.1),
                        ),
                      ),

我想在按下按钮时进行验证

RaisedButton(
            onPressed: () {
           // call validate function from here.....   
        },
        textColor: Colors.white,
        padding: const EdgeInsets.all(0.0),
        child: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: <Color>[
                Color(0xFF0D47A1),
                Color(0xFF1976D2),
                Color(0xFF42A5F5),
              ],
            ),
          ),
          
          child:
              Text('Next', style: TextStyle(fontSize: 20)),
        ),
      ),

请告诉我...

标签: flutter

解决方案


在此处输入图像描述

1.定义验证方法

在这里,我使用email_validator来验证电子邮件和电话号码的正则表达式。您也可以检查intl_phone_field以获取电话号码,或检查libphonenumber(虽然,尚不支持 Web 或桌面):

bool isEmail(String input) => EmailValidator.validate(input);

bool isPhone(String input) => RegExp(
  r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$'
).hasMatch(input);

2. 定义你的TextFormField

然后,在您的 中TextFormField,定义 aGlobalKey<FormFieldState>和 avalidator您测试电子邮件和电话号码的位置:

TextFormField(
  key: _key.value,
  validator: (value) {
    if (!isEmail(value) && !isPhone(value)) {
      return 'Please enter a valid email or phone number.';
    }
    return null;
  },
  decoration: InputDecoration(
    contentPadding: const EdgeInsets.all(16.0),
    hintText: "Enter your phone number or email",
    filled: true,
    fillColor: Colors.grey.withOpacity(0.1),
  ),
),

3.验证TextFormField按下按钮

当用户按下按钮时,验证TextFormField并导航是否有效。

ElevatedButton(
  onPressed: () {
    if (_key.value.currentState.validate()) {
      // Navigate to next page
    }
  },
  style: ButtonStyle(
    padding: MaterialStateProperty.all(const EdgeInsets.all(0.0)),
    foregroundColor: MaterialStateProperty.all(Colors.white),
    backgroundColor: MaterialStateProperty.all(Color(0xFF0D47A1))
  ),
  child: Text('Next', style: TextStyle(fontSize: 20)),
),

完整的源代码

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

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

bool isEmail(String input) => EmailValidator.validate(input);
bool isPhone(String input) =>
    RegExp(r'^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$')
        .hasMatch(input);

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _key = useState(GlobalKey<FormFieldState>());
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextFormField(
              key: _key.value,
              validator: (value) {
                if (!isEmail(value) && !isPhone(value)) {
                  return 'Please enter a valid email or phone number.';
                }
                return null;
              },
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.all(16.0),
                hintText: "Enter your phone number or email",
                filled: true,
                fillColor: Colors.grey.withOpacity(0.1),
              ),
            ),
            const SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                if (_key.value.currentState.validate()) {
                  // Navigate to next page
                }
              },
              style: ButtonStyle(
                  padding: MaterialStateProperty.all(const EdgeInsets.all(0.0)),
                  foregroundColor: MaterialStateProperty.all(Colors.white),
                  backgroundColor:
                      MaterialStateProperty.all(Color(0xFF0D47A1))),
              child: Text('Next', style: TextStyle(fontSize: 20)),
            ),
          ],
        ),
      ),
    );
  }
}

推荐阅读