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.

@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