Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· OpenAIAi2 WildChat-4.8M (AI2)

add regex in flutter input controller that numbers start with 01

  1. User

    add regex in flutter input controller that numbers start with 01

  2. Assistant

    To add a regex pattern in a Flutter TextEditingController that only allows numbers starting with "01", you can use the following code:

    import 'package:flutter/services.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: TextField(
                controller: TextEditingController()..text = '',
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'^01\d*')),
                ],
                keyboardType: TextInputType.number,
              ),
            ),
          ),
        );
      }
    }
    

    In this code:

    • RegExp(r'^01\d*'): The regex pattern ^01\d* is used to allow numbers starting with "01" followed by any digits.

    • FilteringTextInputFormatter.allow(RegExp(r'^01\d*')): This formatter is added to the TextField's inputFormatters property to restrict the input to match the specified pattern.

    Now, the TextField will only allow input that starts with "01" and can be followed by any digits.