flutter textfield phone number validation using regex pattern
flutter textfield phone number validation using regex pattern

Are you looking for a phone number validation regex that you can use with or without a country code, brackets, and dash? Well, look no further! In this Flutter Article, I’ll show you how to create a phone number validation regex in flutter that works with any number format.

Whether you’re looking to validate a phone number in the US, Canada, or any other country, This Phone Number regex pattern will help you get the job done quickly and correctly. Plus, it’s simple to use and easy to customize to suit your needs. So be sure to read this article and learn how to implement a phone number validation in flutter TextField using regex that works with any number format!.

I want a regex that matches following phone number pattern string:-

  • XXXXXXXXXX : 10 digit mobile number validation.
  • +91 XXXXXXXXXX : Country code + 10 digit phone number.
  • (XXX) XXX XXXX : Phone number with brackets separator.
  • (XXX) XXX-XXXX : Number with brackets & dash separator.
  • XXX-XXX-XXXX : Phone Number with dash separator.

Here X defines number

International phone number regex

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$

Explanation of above phone number regex

^\s*Starting line , accept white space at beginning.
(?:\+?(\d{1,3}))?Match country code, here ‘?’ makes it optional. remove ‘?’ to validate phone number and make it mandatory.
[-. (]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Area code of 3 digit in phone number string. add ‘?’ at end to make area code optional.
[-. )]*Match special character like bracket which may appear between the country code & area code.
(\d{3})Exchange Number of 3 digit in phone regex string. add ‘?’ at end to make area code optional.
[-. ]*Match special character like dash which may appear between.
(\d{4})Subscriber number of 4 digit in phone number string.
(?: *x(\d+))?Optional Extensional Number.
\s*$Accept any white space at ending of phone number string.
Mobile Phone number Validation Regular expression

Video Tutorial

Flutter Phone Number TextFormField Validation using Regex Pattern

Complete Source code:- main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  TextEditingController phoneController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
            Form(
              key: _formKey,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextFormField(
                        controller: phoneController,
                        decoration: buildInputDecoration(Icons.phone, "Phone"),
                        keyboardType: TextInputType.phone,
                        onChanged: (value){
                           _formKey.currentState?.validate();
                        },
                        validator: (value){
                          if(value!.isEmpty){
                            return "Please Enter a Phone Number";
                          }else if(!RegExp(r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$').hasMatch(value)){
                            return "Please Enter a Valid Phone Number";
                          }
                        },
                ),
              ),
            )
        ],
      )
    );
  }
}

InputDecoration buildInputDecoration(IconData icons,String hinttext){
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: const BorderSide(
        color: Colors.green,
        width: 1.5
      )
    ),
    border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(25.0),
        borderSide:const  BorderSide(
            color: Colors.blue,
            width: 1.5
        )
    ),
    enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(25.0),
        borderSide:const  BorderSide(
            color: Colors.blue,
            width: 1.5
        )
    ),
  );
}