I was searching for a regex which matches my requirement. But I couldn't find an exact one .
My requirement is
Add validation check to avoid Phone numbers with:
1) 6 digits equal (e.g. 000000 ; 111111)
2) sequence numbers (7 digits) (e.g.
1234567 ; 7654321)
I tried and got this piece of code finally
if (preg_match('/(\d)\1{5}/', $phone)) {
echo "Invalid Phone number";
}
But it matches only the first case. Hope some one will help me. Thanks in advance!
This is one of those times that I'd break away from regex.
This will perform your expected validation (and includes "around-the-clock" number sequences).
PHP Demo
$phone='000000';
$len=strlen($phone);
$rnd_the_clk='0123456789012345';
if(($len==6 && $phone==str_repeat($phone[0],6)) // length is 6, check only one integer used
||
($len==7 && (strpos($rnd_the_clk,$phone)!==false || strpos($rnd_the_clk,strrev($phone))!==false))){ // length is 7, check sequential
echo "invalid";
}else{
echo "valid";
}
Related
What i have done is remove the +92 or 0092 from the start and used the following code to check if it is a valid mobile number for a pakistani person
if(preg_match('/3[0-4][0-9](?:.*)/', $number) == 1) {
//Pakistani mobile number
} else {
// not a pakistani mobile number
}
is this approach right?
Based on the description found on wikipedia: Telephone_numbers_in_Pakistan,
then something like this pattern:
^0?3(?:[0-46]\d|55)\d{7}$
Or without considering the special case of operator 5 (SCO):
^0?3[0-6]\d{8}$
Or with including the country prefix as an optional group:
^((?:00|\+)92)?(0?3(?:[0-46]\d|55)\d{7})$
Php Test Snippet:
<?php
$telnumber='03441234567';
if(preg_match('/^((?:00|\+)92)?(0?3(?:[0-46]\d|55)\d{7})$/', $telnumber))
{
echo "matches pattern";
} else
{
echo "doesn't match pattern";
}
(^\+92[0-9]{10}$)|(^\0092[0-9]{10}$)
Here string append +92 initially then check next 10 digit or if there is 0092 in front of number then it consists of 10 digit number.
The +92 and 0092 check your ISD code initially not other.
For only accept \d{4} and 9 digit ^((0)(3))([0-9]{9})$
Pakistan mobile number examples:
+923331234567
00923331234567
03331234567
try this regex:
"^((?:00|\\+)92)?(0?3(?:[0-4])\\d{7})\$"
((?:00|\\+)92)? -> 0092 or +92 or none
0?3 -> 03 or 3
(?:[0-4]) -> after above string only 0,1,2,3,4 can be accepted (e.g. 031, 032, 033, 034)
\\d{7} -> length 7 characters will be accepted after above string
Note: other country regex can be made from these examples easily
Use the following python code to validate Pakistani Phone Number. It checks country code (+92, 0092, 92, 0) followed by a 3 and then for carrier code of 2 digits with limit of first digit (0 - 4) and limit of second digit (0 - 9) and at the end 7 digits in range (0 - 9).
import re
def validate_not_mobile(value):
pat = re.compile(r'(^((\+92)?(0092)?(92)?(0)?)(3)([0-4]{1})([0-9]{1})([0-9]{7})$)')
if re.fullmatch(pat, value):
print(f"'{value}' is a valid number!")
else:
print(f"'{value}' is NOT a valid number!")
I have tested the code with several test numbers and it has worked fine. If there is any further update I'll update it here.
I am trying to validate 10 digits mobile number using PHP function preg_match. The below code does not produce any output.
Is it the regex wrong? or I am using it incorrectly.
I was expecting Hi True in the output. if it matches or Hi False if it does not match.
<?php
$value = '9987199871';
$mobileregex = "/^[1-9][0-9]{10}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1; // #debug
?>
regex taken from https://stackoverflow.com/a/7649835/4050261
The regex you stated will match eleven digits, not ten. Since all Indian mobile numbers start with 9,8,7, or 6, we can use the following regex:
^[6-9][0-9]{9}$
Here is your code snippet updated:
$value = '9987199871';
$mobileregex = "/^[6-9][0-9]{9}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1;
Note that the above regex is still probably far from the best we could do in terms of validation, but it is at least a start.
The following code snippet will check if the mobile number digits are within 10-15 digits including '+' at the start and followed by a non-zero first digit.
Regular expression
"/^[+]?[1-9][0-9]{9,14}$/"
Code snippet
// Validation for the mobile field.
function validateMobileNumber($mobile) {
if (!empty($mobile)) {
$isMobileNmberValid = TRUE;
$mobileDigitsLength = strlen($mobile);
if ($mobileDigitsLength < 10 || $mobileDigitsLength > 15) {
$isMobileNmberValid = FALSE;
} else {
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $mobile)) {
$isMobileNmberValid = FALSE;
}
}
return $isMobileNmberValid;
} else {
return false;
}
}
^ symbol of the regular expression denotes the start
[+]? ensures that a single(or zero) + symbol is allowed at the start
[1-9] make sure that the first digit will be a non zero number
[0-9]{9,14} will make sure that there is 9 to 14 digits
$ denotes the end
$mob = "9513574562";
if(preg_match("/^\d+\.?\d*$/",$mob) && strlen($mob)==10){
echo 1;
}else{
echo 0;
}
preg_match() checking it is integer or not and in strlen() it is checking no of digit in this string. If 2 condition satisfy then it is a 10 digit valid mobile no
for pakistani mobile number the regex code will be the following
^[9][2][3][0-9]{9}$
I'm trying to match a specific datetime format in PHP's regex:
dd-mm-YYYY HH:ii:ss
It should always be in that format. Meaning that for example when it is the first day of the month there must be a leading zero. E.g.:
01-01-2013 01:01:01
I tried it with the following pattern:
^[0-12]{2}-[0-31]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$
But the above pattern fails on timestamps like: 09-05-2013 19:45:10.
http://rubular.com/r/eGBAhwiNCR
I understand this may not be the correct approach to validate a date time like this, but I really want to know what is wrong with the above.
[0-12]{2} matches not the numbers 0 till 12. Instead it's a character class allowing 0 to 1 and also the number 2. The subsequent quantifier just allows the repetition of those, meanding 0,1 or 2 repeated two times.
Your other placeholders follow the same non-functioning scheme.
It's best to resort to \d{2} or \d{4} if you can't google a better regex. Even better yet, just use DateTime to verify the format.
The problem is when you are checking the "ranges", for example [0-12] at the beginning. That is a character class, and it is telling the regex to match 0 through 1, and then 2. So if you added more numbers in after the 1st one, it isn't working as you are expecting. Changing your regex slightly (focused on the [0-12] initial), [0-319]{2}-[0-12]{2}-[0-9]{4} [0-23]{2}:[0-59]{2}:[0-59]{2}$, would match 09-01-2011 11:11:10.
Ensuring there are valid numbers for each of those spaces requires a little thinking outside the box. The regex:
(0[1-9]|[12][\d]|3[0-2])-(0[1-9]|1[0-2])-[\d]{4} (0[1-9]|1[\d]|2[0-3]):(0[1-9]|[1-5][\d]):(0[1-9]|[1-5][\d])$
will work for what you are expecting with the regex you attempted.
If you break it down into smaller pieces it makes sense (it looks really scary at the beginning). Looking at the first piece (0-31 for "days").
(0[1-9]|[12][\d]|3[0-2])
This is using an or to handle 3 different cases.
0[1-9] - a zero followed by any number between 1-9. We don't want [0-9]{2} since that will allow numbers like 00. So a number is valid if it starts with 0 and has any other number after it (for single digit days).
[12][\d] - a 1 or 2 followed by any digit. This allows the numbers 10-29 to be valid.
3[0-2] - a 3 followed by anything 0 through 2 matching 30, 31, and 32.
Broken down, it's not too bad but this pattern is then carried out for each "field" in your date. So this regex validates on each field being valid... but a better way to confirm valid dates maybe needed. This doesn't get into the complexity of checking if you can have 30-02 for example, where February doesn't have 30 days.
^[0-9]{2}-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}$
The example of validation is in php but the regex is standard
/*pass the date you wanna validate as parameter to the function.
The function returns true if it is valid and false if the date passed is not valid
*/
function DateValid($date){
//format will be fr if the date is in french format and en if the date is in en format
$format='';
//regex that tests if the date is in french format or english, if not in one of these two then it is not valid
if(preg_match("#^(\d{1,2})[\-./ ](\d{1,2})[\-./ ](\d{4})(?: (\d{1,2})(?:[ .-](\d{1,2})){1,2})?$#",$date,$m)){
$format='fr';
}elseif (preg_match('#^(\d{4})[-. ](\d{1,2})[-. ](\d{1,2})(?: (\d{1,2})(?:[ .-](\d{1,2})){1,2})?$#', $date, $m)) {
$format='en';
}else{
echo '<p style="font-size:150px">not english nor french</p>';
return false;
}
//If it is french format or English then check if the date is correct
if($format=='fr'){
if (checkdate($m[2], $m[1], $m[3]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
echo '<p style="font-size:150px">Not valid french</p>';
return false;
}else{
echo '<p style="font-size:150px">Valid french</p>';
return true;
}
}elseif($format=='en'){
if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
echo '<p style="font-size:150px">Not valid english</p>';
return false;
}else{
echo '<p style="font-size:150px">Valid english</p>';
return true;
}
}
}
function sendSms($toPhone,$message){
$toPhone=intval(trim($toPhone));
if(strlen($toPhone)== 8 && $toPhone{0}==9){
//sending sms
}else{
return "error";
}
}
I am trying to validate mobile numbers for sending SMS. The first line trims the phone number string and then converts it to an integer. In the if statement, I want to make sure that the number length is 8 digits and it begins with 9. This function always goes for the else even if the number is correct( 8 digits and begins with 9). What could be the issue here.
Why not regex?
$valid = preg_match('/^9[0-9]{7}$/', trim($phone));
You can remove from $toPhone all not digits
function sendSms($toPhone,$message){
$_phone = '';
for ($i = 0; $i < strlen($toPhone); $i++)
{
if (is_numeric($toPhone[$i]))
$_phone .= $toPhone[$i];
}
if(strlen($_phone)== 8 && $_phone[0]=='9'){
//sending sms
}else{
return "error";
}
}
After you converted the phone number to an integer with $toPhone=intval(trim($toPhone));,, you can't access the digits in the way you are trying with $toPhone{0}, because you operate on a number and not on a string any more.
See this isolated example:
$number = 987654321;
var_dump($number{0}); //NULL
However, substr would be capable of doing this:
$number = 987654321;
var_dump(substr($number, 0, 1)); //string(1) "9"
Converting a whole number to integer isn't a good idea anyways, because users might enter the number with spaces in between or signs like + and /. Better search for an already existing approach to validate phone numbers.
Take a look here, where the topic "validate mobile phone numbers" is covered in more detail: A comprehensive regex for phone number validation
You convert variable to integer and apparently $toPhone[0] works on strings only.
The same function without intval() works as you wanted.
function sendSms($toPhone, $message)
{
$toPhone = trim($toPhone);
if(strlen($toPhone) == 8 && $toPhone[0] == 9){
//sending sms
} else {
return "error";
}
}
i have a phone number in following format +923334173333 and now i want to validate this number exactly in the given format and length with php
Fastest way would be
function validatePhoneNumber($n)
{
return strlen($n) == 13 && $n[0] == '+' && ctype_digit(substr($n, 1)) == 13;
}
validatePhoneNumber('+923334173333'); // returns true
You would need the rules for all possible types of phone numbers and their limitation in the whole world. I'm uncertain if such list even exists.
You can test the length with strlen(), and use ctype_digit() in combination with substr() to check that the substring starting after the '+' consists only of digits.