Skip to main content

Flutter Empty Validation on TextField

TextField widget in flutter comes with errorText property of Input decoration. This property allow us to show a error message if user does not enter any value in TextField. It's like a input validation where we can notify the user to enter text and do not leave empty TextField.

Flutter Empty Validation on TextField

1. Defining Two TextEditingController to manage TextField entered values.
 final nameInput = TextEditingController();
 final lastNameInput = TextEditingController();
2. Creating 2 Boolean type values, Each value manages each TextField empty condition.
 bool nameValidation = false;
 bool lastNameValidation = false;
3. Creating a function checkTextField(), In the function we will putting IF Else condition based upon checking TextField is empty or not condition and updating the Boolean variable value.
 checkTextField() {
    if (nameInput.text.isEmpty) {
      setState(() {
        nameValidation = true;
      });
    } else {
      setState(() {
        nameValidation = false;
      });
    }

    if (lastNameInput.text.isEmpty) {
      setState(() {
        lastNameValidation = true;
      });
    } else {
      setState(() {
        lastNameValidation = false;
      });
    }
  }
4. Creating 4 Static border styles. We are defining these border styles as reusable border styles. So we will use these styles in all TextInput fields.
  static const border = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.green, width: 1.8),
  );

  static const borderError = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.red, width: 1.8),
  );

  static const errorBorderFocus = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.red, width: 1.8),
  );

  static const focusBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(8.0)),
      borderSide: BorderSide(color: Colors.purple, width: 1.8));
5. Creating 2 TextField and 1 Button widget. We will using errorText property with Boolean variable with ternary operator. So if the Boolean variable value is empty(True) then it will show us a error message.
Column(children: <Widget> [
      Container(
          margin: const EdgeInsets.all(10),
          child: TextField(
            controller: nameInput,
            autocorrect: true,
            decoration: InputDecoration(
                hintText: 'Type Here...',
                errorText: nameValidation ? 'Name Cannot be Empty.' : null,
                enabledBorder: border,
                errorBorder: borderError,
                focusedErrorBorder: errorBorderFocus,
                focusedBorder: focusBorder),
          )),
      Container(
          margin: const EdgeInsets.all(10),
          child: TextField(
            controller: lastNameInput,
            autocorrect: true,
            decoration: InputDecoration(
                hintText: 'Type Here...',
                errorText:
                    lastNameValidation ? 'Last Name Cannot be Empty' : null,
                enabledBorder: border,
                errorBorder: borderError,
                focusedErrorBorder: errorBorderFocus,
                focusedBorder: focusBorder),
          )),
      ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
        ),
        onPressed: checkTextField,
        child: const Text('Check TextField Empty ?'),
      ),
    ])
Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: Scaffold(body: Center(child: App())));
  }
}

class App extends StatefulWidget {
  const App({super.key});
  @override
  AppState createState() => AppState();
}

class AppState extends State < App > {
  final nameInput = TextEditingController();
  final lastNameInput = TextEditingController();
  bool nameValidation = false;
  bool lastNameValidation = false;

  checkTextField() {
    if (nameInput.text.isEmpty) {
      setState(() {
        nameValidation = true;
      });
    } else {
      setState(() {
        nameValidation = false;
      });
    }

    if (lastNameInput.text.isEmpty) {
      setState(() {
        lastNameValidation = true;
      });
    } else {
      setState(() {
        lastNameValidation = false;
      });
    }
  }

  static const border = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.green, width: 1.8),
  );

  static const borderError = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.red, width: 1.8),
  );

  static const errorBorderFocus = OutlineInputBorder(
    borderRadius: BorderRadius.all(Radius.circular(12.0)),
    borderSide: BorderSide(color: Colors.red, width: 1.8),
  );

  static const focusBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(8.0)),
      borderSide: BorderSide(color: Colors.purple, width: 1.8));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Center(
                child: Column(children: < Widget >[
      Container(
          margin: const EdgeInsets.all(10),
          child: TextField(
            controller: nameInput,
            autocorrect: true,
            decoration: InputDecoration(
                hintText: 'Type Here...',
                errorText: nameValidation ? 'Name Cannot be Empty.' : null,
                enabledBorder: border,
                errorBorder: borderError,
                focusedErrorBorder: errorBorderFocus,
                focusedBorder: focusBorder),
          )),
      Container(
          margin: const EdgeInsets.all(10),
          child: TextField(
            controller: lastNameInput,
            autocorrect: true,
            decoration: InputDecoration(
                hintText: 'Type Here...',
                errorText:
                    lastNameValidation ? 'Last Name Cannot be Empty' : null,
                enabledBorder: border,
                errorBorder: borderError,
                focusedErrorBorder: errorBorderFocus,
                focusedBorder: focusBorder),
          )),
      ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
        ),
        onPressed: checkTextField,
        child: const Text('Check TextField Empty ?'),
      ),
    ]))));
  }
}
Screenshots:

Flutter Empty Validation on TextField

Flutter Check Text Input is Empty or Not

errorText on Text Field in flutter

Comments