Skip to content

Instantly share code, notes, and snippets.

@homaily
Last active November 14, 2024 13:11
Show Gist options
  • Save homaily/8672499 to your computer and use it in GitHub Desktop.
Save homaily/8672499 to your computer and use it in GitHub Desktop.
Regex to validate saudi mobile numbers

السلام عليكم ، هذا كود ريجيكس بسيط للتحقق من صحة أرقام الجوالات السعودية ، يقوم الريجيكس بالتحقق من مفتاح الدولة ، مفتاح شركة الإتصالات لضمان صحة النص المدخل .

Hello, this is a simple regex to validate saudi mobile numbers, the code will validate country code, telecome company code and make sure the tested sting is correct .

/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/

Regex Breakdown - شرح الكود

/^

التأكد أن النص المدخل في بداية السطر

Start of Line

(009665|9665|\+9665|05|5)

التأكد أن الرقم المدخل يبدأ بمفتاح السعودية أو المفتاح المحلي لأرقام الجوالات

Validate that the contry code is for Saudi Arabia

(5|0|3|6|4|9|1|8|7)

التأكد من مفتاح شركة الإتصالات

Validate thar the telecome company prefix is correct

  • 0, 5, 3 : STC prefix
  • 6, 4 : Mobily prefix
  • 9, 8 : Zain prefix
  • 7 : MVNO prefix (Virgin and Lebara)
  • 1 : Bravo prefix
[0-9]{7}

التحقق من وجود 7 خانات بعد مفتاح الدولة ومفتاح شركة الإتصالات

Validate that the input contains 7 digits after the country code and the telecome prefix.

$/

نهاية السطر

End of Line

Usage Examples - أمثلة لاستخدام الكود

PHP:

preg_match('/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/', '0505330609'); // return true
preg_match('/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/', '0525330609'); // return false

Javascript

var regex = new RegExp(/^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/);
regex.test('0501234567'); // return true;
regex.test('0521234567'); // return false;

thanks to http://twitter.com/motazG, https://twitter.com/ModmenNet and https://twitter.com/engineer_fouad for their help.

@mhewedy
Copy link

mhewedy commented Feb 23, 2021

could be represetnted also as: ^(009665|9665|\+9665|05|5)[013456789][0-9]{7}$

@Monther07
Copy link

يعطيك العافية
حاولت استخدم النمط في ال
HTML + bootstrap 5 validation
واشتغل

<input id="telphone" name="userphone" type="tel" class="form-control" placeholder="0xx xxx xxxx" pattern="(05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})" required>

@AbdullrhmanAljasser
Copy link

Thank you very much

@thepearl
Copy link

Swift 5 Extension :

extension String
{
    func validateSAPhoneNumber() -> Bool
    {
        let PATTERN = #"^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$"#
        return self.range(of: PATTERN ,options: .regularExpression) != nil
    }
}

Usage Example with UITextField :

@IBAction func phoneNumberDidChanged(_ sender: UITextField)
    {
        guard let phoneText = sender.text else { isPhoneNumberValid = false; return }
        
        isPhoneNumberValid = phoneText.validateSAPhoneNumber()

        if isPhoneNumberValid
        {
            UIView.transition(with: view, duration: 0.2, options: .transitionCrossDissolve, animations: { [weak self] in
                guard let self = self else { return }
                self.SigninButton.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
                self.SigninButton.titleLabel?.text = "SignIn".localizedString
                self.SigninButton.layer.backgroundColor = #colorLiteral(red: 0.3562759757, green: 0.7210461497, blue: 0.2551059723, alpha: 1)
            })
        }
        else
        {
            UIView.transition(with: view, duration: 0.2, options: .transitionCrossDissolve, animations: { [weak self] in
                guard let self = self else { return }
                self.SigninButton.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
                self.SigninButton.titleLabel?.text = "SignIn".localizedString
                self.SigninButton.layer.backgroundColor =  #colorLiteral(red: 0.2823529412, green: 0.6901960784, blue: 0.2549019608, alpha: 1).withAlphaComponent(0.5).cgColor
            })
        }
    }

@Waseem-Almoliky
Copy link

Waseem-Almoliky commented Apr 2, 2021

could be represetnted also as: ^(009665|9665|\+9665|05|5)[013456789][0-9]{7}$

or as

/^((\+|00)9665|0?5)([013456789][0-9]{7})$/

@ahmad-511
Copy link

/^((+|00)9665|0?5)([013456789][0-9]{7})$/

or maybe as

/^((\+|00)9665|0?5)([013-9][0-9]{7})$/

Thanks everybody

@SerroCSC
Copy link

SerroCSC commented Dec 7, 2021

شكرا

@Dev-Zinab
Copy link

يعطيك العافية، استفدت من الكود

@nawafinity
Copy link

Good job,
Here is an more optimized regex:

/^(:?(\+)|(00))?(:?966)?+(5|05)([503649187])([0-9]{7})$/

https://regex101.com/r/nPngzj/1

@ahmedsafadii
Copy link

python

def check_mobile_validate(mobile):
    regex = re.compile(r"^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$", flags=re.IGNORECASE)
    return regex.search(mobile)

@Bilal-Elmursi
Copy link

If you are using C#, you will need to remove / at the start and the end of the string.

var regex = new Regex(@"^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$");
return regex.IsMatch(mobileNumber);

@fearschism
Copy link

اشكرك منقذ!!

@hasher313
Copy link

hasher313 commented Oct 31, 2022

Dart/Flutter

RegExp regex =
        RegExp(r'^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$');
if(regex.hasMatch(phoneNumber)){
}else{
}

@ahmed-alhelali
Copy link

So grateful!
thanks a lot, and you also @hasher313

@MohammadEdrees
Copy link

MohammadEdrees commented Jan 17, 2023

تسلم ايدك يا هندسة
^(009665|9665|+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$
ده شغال#C ممكن تضيفه عندك لو حابب
مثال بال #C

using System;

using System.Text.RegularExpressions;

public class Example

{

public static void Main()
{
    string pattern = @"^(009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$";

    string input = @"+966566846511";

    RegexOptions options = RegexOptions.Multiline;
    
    foreach (Match m in Regex.Matches(input, pattern, options))
    {
        Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
    }
}

}

@almgwary
Copy link

جزاك الله خيرا

@Saraa-39
Copy link

يعطيك العافية , تعرف كيف اطبقه باستخدام flutter ?

@almgwary
Copy link

almgwary commented May 14, 2023

يعطيك العافية , تعرف كيف اطبقه باستخدام flutter ?

bool matchesRegex(String input, String pattern) {
  RegExp regex = new RegExp(pattern);
  return regex.hasMatch(input);
}

@mohammedterfa
Copy link

جزاك الله خير

@Sal7one
Copy link

Sal7one commented Oct 1, 2023

Support for telephone numbers (((009665|9665|\+9665|05|5)(5|0|3|6|4|9|1|8|7))|((0096601|96601|\+96601|01)(1|2|3|4|6|7)))([0-9]{7})

@excalibur1987
Copy link

جزاك الله خيراً، لكن هل هناك خدمة ما للتأكد من أن الرقم بالحقيقة فعال؟

@Ly0kha
Copy link

Ly0kha commented Sep 4, 2024

I have tried to embed it into Laravel Validation, but an error occured!!
$validation = Validator::make($data->all(), array(
//'title'=> 'required',
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'gender' => 'required',
'group' => 'required',
'image' => 'mimes:png,jpeg,bmp|max:2024',
'mobile' => 'regex:/^(009665|9665|+9665|05|5)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/',
));
and another question, if I entered 966 in the start, does it works?

$validation = Validator::make($data->all(), [
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $id,
'gender' => 'required',
'group' => 'required',
'image' => 'mimes:png,jpeg,bmp|max:2024',
'mobile' => 'regex:/^(009665|9665|+9665|05|5|966)(5|0|3|6|4|9|1|8|7)([0-9]{7})$/',
]);
Just escaped the + sign, and added support for 966 as a valid start. Should work now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment