How to validate email in a TextFormField - flutter

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: validateEmail,
),
)
then the validation function
String? validateEmail(String? value) {
const pattern = r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'"
r'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-'
r'\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*'
r'[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4]'
r'[0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9]'
r'[0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\'
r'x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])';
final regex = RegExp(pattern);
return value!.isNotEmpty && !regex.hasMatch(value)
? 'Enter a valid email address'
: null;
}
Link to regex https://stackoverflow.com/a/201378/12695188

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
Add dependency to your package's pubspec.yaml file:
dependencies:
validators: ^2.0.0 # change to latest version
Run from the command line:
$ pub get
// on VSCode u need not do anything.
Import in your Dart code:
import 'package:validators/validators.dart';
Validate your field
Form(
child: TextFormField(
validator: (val) => !isEmail(val) ? "Invalid Email" : null;,
),
)

QUICK FIX 🙂
Use this in your TextFormField.
validator: (value) {
if(value == null || value.isEmpty || !value.contains('#') || !value.contains('.')){
return 'Invalid Email';
}
return null;
},

The previous answers all discuss options for verifying a TextFormField in a Form. The question asks about doing this in
TextFormField or TextField
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,
),

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(),
]),
),

TextFormField(
validator: (value) {
if(value.isEmpty) {
return "Please enter email";
} else if(!value.contains("#")) {
return "Please enter valid email";
}
},
decoration: InputDecoration(hintText: 'email'),
),

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.

Related

Flutter TextFormField with non-const decoration

I want to write something like a function that generates TextFormFields with different names, but I don't want the labelText attribute to be const. That way I can easily rubber stamp out a bunch of similar fields that have different names.
For example
TextFormField myFormField(myMapType myMap, String fieldName) {
return TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: fieldName,
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your $fieldName';
}
return null;
},
initialValue: myMap.attribute[fieldName],
onSaved: (val) {
setState(
() {
myMap.setAttribute(fieldName, val!);
},
);
});
}
But that gives an error "Invalid constant value" at the line "labelText: fieldName". What's the trick needed to accomplish what I'm trying to do? Or what dumb mistake did I make?
fieldName will get on runtime rather than compile time. Therefore you cant use const
You can do
return TextFormField(
decoration: InputDecoration(
border: const OutlineInputBorder(), //this can be const
labelText: fieldName,
),
validator: (value) {
You can check What is the difference between the "const" and "final" keywords in Dart?

How to Restrict special characters like except numbers 0 to 9 in onchanged for textfield

The following is my onChanged method for phone number textfield. I want only numbers to be accepted. but it is accepted all characters except alphabets a-z and A-Z
onChanged: (value) {
if (value.contains(RegExp(r'[a-z,A-Z]')) ||
value.isEmpty) {
setState(() {
_isPhone = false;
});
make use of InputKeyboardtype
Only allow number input in flutter text field Flutter
TextFormField(
initialValue: _tip.toString(),
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number,
decoration: InputDecoration(
prefix: Text('\$'),
labelText: 'Enter Custom Tip Amount ',
hintStyle: TextStyle(fontWeight: FontWeight.w600)),
onChanged: (val) => setState(() => _tip = int.tryParse(val) ?? 0),
),
Use input formatter
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
Add this to your textfield and/or if you wish to check the number in on changed then you can try this
onChanged : (value) {
final valueNum = num.tryParse(value);
if(valueNum == null) {
//Not phone
return;
}
//Is phone. Setstate here as phone true
}

Remove error message in TextFormField in Flutter

Hi I want to remove error message caused by validator in TextFormField widget after I submit a form in flutter.
Ps : I want the error message disappeared after I select again the TextFormField to write into it again.
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null ||
value.isEmpty ||
!EmailValidator.validate(value)) {
return nullEmailMsg;
}
return null;
},
decoration: InputDecoration(
hintText: emailHint,
prefixIcon: Icon(Icons.mail),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
If you put your TextFormField inside a Form with the property autovalidateMode: AutovalidateMode.onUserInteraction, the validation function should trigger when you select again or change the text.
If the validation function is satisfied, the error message will be removed.
You have to use the autoValidateMode method in TextFormField.
Here, is the some of the reference:
https://api.flutter.dev/flutter/widgets/AutovalidateMode-class.html

Flutter - Textfield reaction when focus changes

I've made a program where the user can create an account, but I've placed some restrictions on the textfields (like for the First Name, it can only accept a string made of A-Z or a-z).
I want an "error text" to show under the textfield if the input is wrong (like if the user types "John1"), but I don't know how to do this. The simple way would be to use the onEditingComplete but this only works if the user taps on the keyboard the "done" key.
Is there a way to make the "error text" appear when the focus changes from one textfield to another?
You can use the validator property of the textfield to do this. It is recommended to encapsulate your fields in a Form() widget and then use the FormTextField() widget to implement your validations, this will enable an error to be shown at the bottom of the text field, if focus changes, or submission is attempted.
Example:
TextFormField(
onSaved: (String value) {},
validator: (String value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
)
The error will appear below in red fonts.
If you want to show error text whenever text/value changed you can do this.
In TextField 'onChanged' validate the user input using some regex and check for error ,if there is an error using TextField decoration 'errorText' property you can show required error.
Widget phoneNumberTextField() {
return Padding(
padding: EdgeInsets.fromLTRB(25, 10, 25, 10),
child: TextField(
style: TextStyle(color: Colors.white),
controller: _phoneNumberController,
maxLength: Constants.PhoneNumberTextFieldMaxLength,
onChanged: (value) {
_phoneNumberErrorText =
validatePhoneNumberTextField(_phoneNumberController.text);
_hasPhoneNumberError = _phoneNumberErrorText.isNotEmpty;
setState(() {});
},
keyboardType: TextInputType.number,
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green, width: 1.0),
),
errorText: _hasPhoneNumberError ? _phoneNumberErrorText : null),
),
);
}
String validatePhoneNumberTextField(String text) {
String errorText = '';
if (text.length < 1) {
errorText = 'Phone Number should not be empty';
} else if (text.length != 10) {
errorText = 'Please enter valid phone number.';
}
return errorText;
}

Showing an error under a TextField in Flutter

Material design allows a text field to indicate an error via a small red label under the input box: https://material.io/components/text-fields (see screenshot below).
Is there a way to achieve this for a TextField field in Flutter? I expected this to be a property of either TextField or TextEditingController, but haven't found anything like it.
It is present in the decoration property in TextField, also you can style it using it's style property.
TextField(
decoration: InputDecoration(
errorStyle: TextStyle(),
errorText: 'Please enter something'
),
),
You show errors based on the validation results which are returned by the validator function provided by TextFormField, You check for some conditions there and return an error message or null based on what you want to show and when, or if you don't want to show anything.
child: new TextFormField(
autocorrect: false,
validator: (value) {
if (value.isEmpty) {
return 'Error Message';
}
return null;
},
onSaved: (val) => //do something...,
decoration: new InputDecoration(labelText: "Label*"),
),