Open In App

Flutter – Restrict TextField to Input Special Characters

Last Updated : 26 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, user input validation is essential for maintaining data integrity and ensuring a smooth user experience. One common requirement is to restrict the input of special characters in a TextField to prevent unwanted characters in certain fields, such as usernames or any other text-based input. In this article we are going to implement a TextField in Flutter that restricts the input of Special Characters In Simple Words we cannot Enter Special Characters into the TextField. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp and the Scaffold , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyTextField(),
    );
  }
}


Step 5: Create MyTextField Class

The MyTextField class is a Flutter StatefulWidget that defines a text input field with the purpose of restricting the input to exclude special characters. It utilizes a TextEditingController to manage the text input and applies an input formatter that denies the entry of specific special characters using a regular expression. The widget is presented within a Scaffold and styled with InputDecoration, providing a labeled text field to prompt users to enter text without including special characters specified in the regular expression. This class serves as a reusable component for creating text input fields with restricted character sets in a Flutter application.

Dart




class MyTextField extends StatefulWidget {
  @override
  _MyTextFieldState createState() => _MyTextFieldState();
}
  
class _MyTextFieldState extends State<MyTextField> {
  // Controller for managing the text input
  final TextEditingController _controller = TextEditingController();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Restricting Special Characters in TextField'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0), 
          child: TextField(
            controller: _controller,
  
            // Input formatter to deny special characters
            // using a regular expression
            inputFormatters: [
              FilteringTextInputFormatter.deny(
                  RegExp(r'[!@#$%^&*(),.?":{}|<>]'))
            ],
  
            // Decoration for the TextField
            decoration: InputDecoration(
              labelText: 'Enter text (no special characters)',
            ),
          ),
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyTextField(),
    );
  }
}
  
class MyTextField extends StatefulWidget {
  @override
  _MyTextFieldState createState() => _MyTextFieldState();
}
  
class _MyTextFieldState extends State<MyTextField> {
  // Controller for managing the text input
  final TextEditingController _controller = TextEditingController();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Restricting Special Characters in TextField'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0), 
          child: TextField(
            controller: _controller,
  
            // Input formatter to deny special characters
            // using a regular expression
            inputFormatters: [
              FilteringTextInputFormatter.deny(
                  RegExp(r'[!@#$%^&*(),.?":{}|<>]'))
            ],
  
            // Decoration for the TextField
            decoration: InputDecoration(
              labelText: 'Enter text (no special characters)',
            ),
          ),
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads