Home > Net >  Flutter TextField regex clears text input
Flutter TextField regex clears text input

Time:10-10

I have a TextField where I want to allow only digits, my phone keyboard for number input also contains . & - characters. So I have the following regex to prevent these 2 characters. It works but my problem is that if I write a number then insert any of these, the whole text input is cleared. I also tried FilteringTextInputFormatter.allow(RegExp(r'^[0-9]*$')) but it behaves the same.

How can I just prevent these 2 from being inserted rather than delete the whole input if any of these 2 are present?

                              TextField(
                                inputFormatters: [
                                  FilteringTextInputFormatter.allow(RegExp(r'^[^.-]*$')),
                                ],
                                controller: _phoneTextController,
                                enableInteractiveSelection: false,
                                keyboardType: TextInputType.number,
                                decoration: InputDecoration(
                                  fillColor: Colors.transparent,
                                  border: InputBorder.none,
                                  focusedBorder: InputBorder.none,
                                  enabledBorder: InputBorder.none,
                                  errorBorder: InputBorder.none,
                                  disabledBorder: InputBorder.none,
                                  hintText: 'number',
                                  hintStyle: HintTextFieldStyle,
                                ),
                                style: TextFieldStyle,
                              ),

CodePudding user response:

Change your input formatter regex:

FilteringTextInputFormatter.allow(RegExp(r'^[^.-]*')),
  • Related