Search code examples
flutterflutter-layouttextinputlayout

How to limit special characters in textinput in Flutter?


I want to use only Alphabat, space and "-" for name input using "Textinput".

Usage:- For user name input we don't want to allow user to enter "(,),$,%,&,*" characters.


Solution

  • Update WhitelistingTextInputFormatter is depreacted now please use FilteringTextInputFormatter

    Example

        inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^ ?\d*')),]
        inputFormatters: [FilteringTextInputFormatter.deny(' ')]
        inputFormatters: [FilteringTextInputFormatter.digitsOnly]
    

    You can use WhitelistingTextInputFormatter for input text as you expect with RegExp.

                        TextFormField(
                            controller: _titleTextController,
                            validator: _titleValidator,
                            decoration: InputDecoration(
                                labelText: "Title",
                                suffixIcon: GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      _titleTextController.text ="";
                                    });
                                  },
                                  child: Icon(Icons.clear),
                                )
                            ),
                            inputFormatters: [
                            // @depreacted WhitelistingTextInputFormatter(RegExp("[a-zA-Z -]"))
                             inputFormatters: [FilteringTextInputFormatter.allow(RegExp("[a-zA-Z -]"))]
                            ],
                          )
    

    For more you can refer this : https://api.flutter.dev/flutter/services/TextInputFormatter-class.html