I'm using TextFormField in Flutter to input email for register page.
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"
input : [email protected]
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)
)),
CodePudding user response:
You can use it to validate email, tell me if have any problem
bool isEmail = RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'* -/=?^_`{|}~] @[a-zA-Z0-9] \.[a-zA-Z] ").hasMatch(your_email_here);
CodePudding user response:
You need to wrap your TextFieldForm inside a Form and set the validator for it. 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';
}
),
),
),
),
),
);
}
}