There is a way to validate the input of the user with a TextFormField or TextField,to reject the input if it's not an email.
There is a way to validate the input of the user with a TextFormField or TextField,to reject the input if it's not an email.
You can use regex for this
Form and TextFormField like so
Form(
autovalidateMode: AutovalidateMode.always,
child: TextFormField(
validator: (value) => validateEmail(value),
),
)
then the validation function
String validateEmail(String? value) {
String pattern =
r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]"
r"{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]"
r"{0,253}[a-zA-Z0-9])?)*$";
RegExp regex = RegExp(pattern);
if (value == null || value.isEmpty || !regex.hasMatch(value))
return 'Enter a valid email address';
else
return null;
}
To validate the form, you can use the autovalidate flag and set up a validator for email. There are many options, including regex or manually writing your own checker, but there are also packages available which implement email checking already.
For example, https://pub.dev/packages/email_validator.
To use it, add it to your pubspec:
dependencies:
email_validator: '^1.0.0'
import 'package:email_validator/email_validator.dart';
...
Form(
autovalidate: true,
child: TextFormField(
validator: (value) => EmailValidator.validate(value) ? null : "Please enter a valid email",
),
)
There are many other validation packages, some of which support may different types of validation. See this search for more https://pub.dev/packages?q=email+validation.
TextFormField(
validator: (val) => val.isEmpty || !val.contains("@")
? "enter a valid eamil"
: null,
decoration: InputDecoration(hintText: 'email'),
),
In the validator first we are checking if the formfeild is empty and also we are checking if the text entered dose not contains "@" in it . If those conditions are true then we are returning a text "enter a valid email" or else we are not returning anything
I suggest use of this excellent library called validators
pubspec.yaml file: dependencies:
validators: ^2.0.0 # change to latest version
$ pub get
// on VSCode u need not do anything.
import 'package:validators/validators.dart';
Form(
child: TextFormField(
validator: (val) => !isEmail(val) ? "Invalid Email" : null;,
),
)
The previous answers all discuss options for verifying a TextFormField in a Form. The question asks about doing this in
TextFormFieldorTextField
TextField does not support the validator: named parameter but you can use any of the previously mentioned techniques to check the validity of the email every time the user modifies the email address text. Here is a simple example:
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
setState(() {
_email = value;
_emailOk = EmailValidator.validate(_email);
});
},
decoration:
kTextFieldDecoration.copyWith(hintText: 'Enter your email'),
),
You can use the validation result as you see fit. One possibility is to keep a login button deactivated until a valid email address has been entered:
ElevatedButton(
child: Text('Log In'),
// button is disabled until something has been entered in both fields.
onPressed: (_passwordOk && _emailOk) ? ()=> _logInPressed() : null,
),
No need to use external libraries or Regex! Put your text field inside a form, set autovalidate to 'always' and inside TextFormField add a validator function:
Form(
autovalidateMode: AutovalidateMode.always,
child: TextFormField(
validator: validateEmail,
),
)
Validator function:
String? validateEmail(String? value) {
if (value != null) {
if (value.length > 5 && value.contains('@') && value.endsWith('.com')) {
return null;
}
return 'Enter a Valid Email Address';
}
note: length > 5 because '.com' and '@' make 5 characters.
QUICK FIX Use this in your TextFormField.
validator: (value) {
if(value == null || value.isEmpty || !value.contains('@') || !value.contains('.')){
return 'Invalid Email';
}
return null;
},
If you use flutter_form_builder with flutter_builder_validators
email verification can be done easily
FormBuilderTextField(
name: 'email',
decoration: InputDecoration(
labelText: 'Email',
errorText: _emailError,
),
validator: FormBuilderValidators.compose([
FormBuilderValidators.required(),
FormBuilderValidators.email(),
]),
),