Validate TextFormField in Flutter, used to create text input fields, is a key Flutter component. Flutter Textformfield validation ensures that user input is valid and meets certain criteria. Validation basics, types, and Textformfield widget validation will be covered.
What is Validation TextFormField?
Validation TextFormField is the process of determining if the user’s input in a Textformfield widget is correct. Validating input entails examining it for specific characteristics, like an email address, password, or a mandatory field, among others. User input that doesn’t meet requirements generates an error message.
What Benefits of Validation TextFormField?
Validation TextFormField checks that user input is correct and meets predefined standards. This reduces the likelihood of mistakes and boosts usability. The app can notify the user and prevent submission of the form if an incorrect email address is entered.
Types of Validation TextFormField
Textformfield widgets support multiple forms of validation. Among the most typical are:
Required validation
This validation requires a value in the input field. Errors appear if the user submits the form without entering anything.
Email validation
Email validation checks for valid email addresses. This prevents app-sent email errors.
Password validation
A valid password is one that can be entered into the input field without error. This can help guarantee that the password is secure by meeting requirements like having at least 8 characters and a mix of letters, numbers, and special characters.
Number validation
Validation of numbers ensures that only valid numbers are entered by the user. Errors in calculations and other work with numerical data may be reduced as a result.
Regular expression validation
Regular expression validation lets developers create custom validation rules. Validating input that doesn’t fit the predefined validation types is possible with this.
Implementing Textformfield validation in Flutter
Flutter provides multiple options for validating Textformfield. Using the pre-existing validators the framework supplies is the quickest and easiest option. These validators verify email addresses and numbers.
Basic Validation TextFormField Using Built-in Validators
The “validator” property of a Textformfield widget lets us use a built-in validator. We can use the “EmailValidator” from the “form_builder_validators” package to check if the user entered a valid email address:
TextFormField( keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelText: 'Email', ), validator: FormBuilderValidators.email(context), );
Custom Validation TextFormField using Validator Function
Custom validator functions allow more complex validation logic. Validator functions return strings if errors occur and null otherwise. A custom validator function can check if a password is at least 8 characters and contains letters, numbers, and symbols:
String? validatePassword(String? value) { if (value == null || value.isEmpty) { return 'Password is required'; } if (value.length < 8) { return 'Password must be at least 8 characters long'; } if (!RegExp(r'^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$').hasMatch(value)) { return 'Password must contain letters, numbers, and symbols'; } return null; } TextFormField( obscureText: true, decoration: InputDecoration( labelText: 'Password', ), validator: validatePassword, );
Output
Displaying Validation TextFormField Errors to the User
We must notify users of validation errors. Use the Textformfield widget’s errorText
property. This property takes a string with the error message to display. The “autovalidateMode” property can validate input as the user types.
final _formKey = GlobalKey<FormState>(); TextFormField( keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelText: 'Email', ), validator: FormBuilderValidators.email(context), autovalidateMode: AutovalidateMode.onUserInteraction, errorText: _formKey.currentState?.validate() != true ? 'Please enter a valid email address' : null, );
Output
Full code
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { final String title = 'Textformfield Validation Example'; @override Widget build(BuildContext context) { return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Row(children: [ Image.asset( 'assets/logo.png', height: 30, ), Text('flutterflux.com') ]), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Please enter your email address:', style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, ), ), SizedBox(height: 8.0), EmailTextFormField(), SizedBox(height: 16.0), ElevatedButton( onPressed: () {}, child: Text('Submit'), ), ], ), ), ), ); } } class EmailTextFormField extends StatefulWidget { @override _EmailTextFormFieldState createState() => _EmailTextFormFieldState(); } class _EmailTextFormFieldState extends State<EmailTextFormField> { final GlobalKey<FormState> _emailKey = GlobalKey<FormState>(); final GlobalKey<FormState> _passKey = GlobalKey<FormState>(); final TextEditingController _textEditingController = TextEditingController(); String? _validateEmail(String? value) { if (value == null || value.isEmpty) { return 'Email is required'; } if (!RegExp(r'^.+@[a-zA-Z]+\.{1}[a-zA-Z]+(\.{0,1}[a-zA-Z]+)$') .hasMatch(value)) { return 'Please enter a valid email address'; } return null; } String? validatePassword(String? value) { if (value == null || value.isEmpty) { return 'Password is required'; } if (value.length < 8) { return 'Password must be at least 8 characters long'; } if (!RegExp(r'^(?=.*?[A-Za-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$') .hasMatch(value)) { return 'Password must contain letters, numbers, and symbols'; } return null; } @override void dispose() { _textEditingController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column(children: [ Form( key: _emailKey, child: TextFormField( controller: _textEditingController, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( border: OutlineInputBorder(), hintText: '123456', ), validator: validatePassword, autovalidateMode: AutovalidateMode.onUserInteraction, onSaved: (value) { // Do something with the value }, )), Form( key: _passKey, child: TextFormField( controller: _textEditingController, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( border: OutlineInputBorder(), hintText: '[email protected]', ), validator: _validateEmail, autovalidateMode: AutovalidateMode.onUserInteraction, onSaved: (value) { // Do something with the value }, ), ) ]); } }
This example has a simple email address form. A custom validator function validates user input from a Textformfield widget. If the email address is invalid, the validator function displays an error message. The autovalidateMode
property validates input as the user types, and the errorText
property displays the error message.
In this example, we used a GlobalKey to access the form state and manually trigger validation when the user presses Submit
. If you need to take action after the form is validated and submitted, this is optional but useful.
Best Practices for Validation TextFormField
To ensure that Textformfield validation is effective and provides a good user experience, here are some best practices to follow:
- Error messages should be simple to understand and offer concrete guidance on how to fix the problem.
- Check for errors in real time as the user types: This can be useful for giving the user instant feedback and discouraging them from entering incorrect information.
- Make use of both pre-existing and user-created validators to make sure input satisfies all requirements and avoids typical mistakes.
- The user experience can be improved and errors avoided by using the correct input type, such as “emailAddress” or “number.”
- Ensure the validation logic is working as expected and producing the desired results by giving it a thorough test.
Conclusion
Validation TextFormField is crucial when building Flutter mobile apps. The user experience can be enhanced and errors avoided by using this to verify that the user’s input is correct and conforms to predetermined standards. Flutter Validation TextFormField options include both built-in validators and user-defined validator functions. We can make reliable, effective forms that deliver a pleasant user experience by sticking to best practices and rigorously testing the validation logic. read too How to Add Swipe Actions Flutter