[英]Flutter TextFormField : Required a special character inside of textformfield input
I'm using TextFormField in Flutter to input email for register page.我在 Flutter 中使用 TextFormField 为注册页面输入电子邮件。
What I want is if there's no char '@' and '.'我想要的是如果没有字符“@”和“。” then it will get rejected.那么它将被拒绝。
This is the result I hope for :这是我希望的结果:
input : name输入:姓名
errorText : "You should enter valid email address" errorText : "您应该输入有效的电子邮件地址"
input : name@gmail.com输入:name@gmail.com
response : success回复:成功
And this is my code :这是我的代码:
TextFormField(
keyboardType: TextInputType.emailAddress,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp("[a-z0-9@._-]")),
],
onChanged: (text) {
_onSearchChanged(text);
},
controller: emailController,
decoration: InputDecoration(
errorText:
isEmailInvalid ? "Email is already taken" : null,
hintText: 'Enter your email',
suffixIcon: isEmailvalid
? const Icon(
Icons.check,
color: Colors.green,
)
: const Icon(
Icons.check_circle,
color: Colors.transparent)
)),
您可以使用它来验证电子邮件,如果有任何问题请告诉我
bool isEmail = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(your_email_here);
You need to wrap your TextFieldForm inside a Form and set the validator for it.您需要将 TextFieldForm 包装在 Form 中并为其设置验证器。 You can refer to this example code:你可以参考这个示例代码:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: Form(
autovalidateMode: AutovalidateMode.always,
onChanged: () {
Form.of(primaryFocus!.context!)!.save();
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(200, 50)),
child: TextFormField(
validator: (String? value) {
return value != null && RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+").hasMatch(value) ? null : 'Invalid email';
}
),
),
),
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.