Jackson
Jackson

Reputation: 41

Regular Expression for International Phone Number

I am working on a flutter app that should validate a phone number. I want to use a regex expression for validation. all numbers should start with +260. The 4th digit can either be a 7 or 9 and the rest of the 8 digits should be any digits between 0-9. Can you help me achieve this? for example, the full number should be (+260(7 or 9)********). I tried using the below expression in my code its not working.

              validator: (value) {
                if (value!.isEmpty) {
                  return 'Phone number cannot be empty';
                }
                if (!RegExp(r'^\+260[79][567]\d{7}$').hasMatch(value)) {
                  return 'Enter valid number';
                }
                return null;
              },

Upvotes: 0

Views: 4438

Answers (2)

Zed Programmer
Zed Programmer

Reputation: 1

^+260[79]\d{8}$

So, the complete regex ensures that the string starts with "+260", followed by either a 7 or 9, and then followed by exactly 8 digits.

You can use this regex expression in your code for validation. If you encounter any issues, let me know, and I can assist you further!

Upvotes: 0

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

^\+(?:\d\s?){6,14}\d$

EXPLANATION

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  \+                       '+'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (between 6 and
                           14 times (matching the most amount
                           possible)):
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
    \s?                      whitespace (\n, \r, \t, \f, and " ")
                             (optional (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  ){6,14}                  end of grouping
--------------------------------------------------------------------------------
  \d                       digits (0-9)
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

Upvotes: 1

Related Questions