Validating International Phone Numbers in PHP [duplicate] - php

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 4 years ago.
I've been searching for hours to find a regex that does this for me, all the ones I've found either require dashes or limit something else that I don't need.
Like this one:
^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Basically I want to allow these types of input for phone number, these are all valid:
+000 111111111
+00011111111111
0022 111111111111
0022111111111
+333-4444-5555-6666
000-7878787-0000-4587
Note that the number of digits is not limited, I only want the validation to filter out empty inputs and the alphabet. Also filter out all other characters except a maximum of 4 dashes, max. 4 spaces and an optional single plus sign.
Is this possible through preg_match or not?
Any help is appreciated, thanks!

Sure its possible. But to my opinion dangerous to use stuff that is not understood. I would do something like this
^(?!(?:\d*-){5,})(?!(?:\d* ){5,})\+?[\d- ]+$
See it here on Regexr
The last part \+?[\d- ]+ allows an optional + followed by at least one digit, dash or space
The negative lookaheads ensure that there are not more than 4 dash or spaces.
Limitations:
- The dash or space can be in one row
- it accepts also - as valid
Try it yourself on the Regexr link, you can just add examples what you want.

Strip wanted characters out (" ", "-"), count the amount then chuck an if statement if count <= 4 (for the "+" character it would be == 1). So in total it would be
if (countSpace <= 4 && countDash <= 4 && countPlus == 1) {
...
}
As for being empty, just use the standard form validation for checking if the input has been filled or not.

Related

Matching string that contains asterisk [duplicate]

This question already has answers here:
Reference - What does this regex mean?
(1 answer)
Regular expressions: Ensuring b doesn't come between a and c
(4 answers)
Closed 3 years ago.
I know this sounds easy but I am stuck.
I want to match strings that has asterisk *.
Essentially I want to allow strings having asterisk at front/back/both but not middle:
(At max there will be 2 asterisks, front and both but no middle, and the presence string is a must)
ALLOW:
*string* *string string* string
DENY:
*str*ing*
*str*ing str*ing* str*ing
*string*****
I tried
^\\*?((?!\\*).)*\\\*?$
and somehow it works.
Can someone explains how this works?
And verify if this is correct because regex..hard to debug and check..
You can use the following regex:
^\*?\w+\*?$
demo: https://regex101.com/r/vwuXv2/1/
Explanations:
^ anchor imposing the start of a line
\*? a * appearing at most one time
\w+ at least 1 word char appearing in the text ([a-zA-Z0-9_] feel free to change it depending on your need)
\*? a * appearing at most one time
$ end of line anchor
Now if you are interested in partial line matches, you can use the following regex:
(?<=^| )\*?\w+\*?(?=$| )
demo: https://regex101.com/r/vwuXv2/2/
Explanations: you add lookbehind, lookahead assertions.
Adding Japanese characters as requested in the comment (add in [^*\s] all the characters you need to exclude from the words):
^\*?[^*\s]+\*?$
demo: https://regex101.com/r/RaCmwt/1/
or
^\*?[[:alpha:]]+\*?$
(with unicode flag enabled) or just
^\*?\p{L}+\*?$
demo: https://regex101.com/r/RaCmwt/2/
You can simply say: Optionally start with asterisk, 0 or more arbitrary characters except asterisk, optionally end with asterisk.
^\*?[^*]*\*?$
https://regex101.com/r/bibCEc/2
An alternative is to inverse the match and test if there is not ( i.e. if(!...)) any asterisk not at the begin or end using negative look behind and look ahead:
(?<!^)\*(?!$)
https://regex101.com/r/8St0M4/2
According to your recent edit you would use the quatifier + to match 1 or more characters:
^\*?[^*]+\*?$
https://regex101.com/r/bibCEc/3

format and trim number

Is there a way In PHP to just get the first two digits from any given number so for instance:
get 17 from 1700,
14 from 1457,
13 from 130
and if digits are single or double digits leave them as they are.
And at last is there a way to find out if the last two digits of four digit number are zeros so, for instance, distinguish 1700, 1600 etc.
(1) To get the first two digits in php you'll want to use the substr method, as described here:
http://php.net/manual/en/function.substr.php
(2) I'm not clear on what you mean by "leave them as they are" here:
if digits are single or double digits leave them as they are.
(3) For searching for characters in a larger string I would suggest using regular expressions as described here:
http://php.net/manual/en/reference.pcre.pattern.syntax.php
Please note, PCRE regular expressions are a very broad subject, so be sure you really need them. A famous quip about programmers and problems comes to mind.
if (substr($foo, -2) == 00) { // Check if last two digits are zero
echo "double zero!"; // Do something if they are
}
if (strlen($foo) > 2) { // Check if there are more than 2 digits
$foo = substr($foo, 0, 2); // If so only return the first 2 digits
}
echo $foo;

Regex for password ver [duplicate]

I need a regular expression with condition:
min 6 characters, max 50 characters
must contain 1 letter
must contain 1 number
may contain special characters like !##$%^&*()_+
Currently I have pattern: (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,50})$
However it doesn't allow special characters, does anybody have a good regex for that?
Thanks
Perhaps a single regex could be used, but that makes it hard to give the user feedback for which rule they aren't following. A more traditional approach like this gives you feedback that you can use in the UI to tell the user what pwd rule is not being met:
function checkPwd(str) {
if (str.length < 6) {
return("too_short");
} else if (str.length > 50) {
return("too_long");
} else if (str.search(/\d/) == -1) {
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+]/) != -1) {
return("bad_char");
}
return("ok");
}
following jfriend00 answer i wrote this fiddle to test his solution with some little changes to make it more visual:
http://jsfiddle.net/9RB49/1/
and this is the code:
checkPwd = function() {
var str = document.getElementById('pass').value;
if (str.length < 6) {
alert("too_short");
return("too_short");
} else if (str.length > 50) {
alert("too_long");
return("too_long");
} else if (str.search(/\d/) == -1) {
alert("no_num");
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
alert("no_letter");
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+\.\,\;\:]/) != -1) {
alert("bad_char");
return("bad_char");
}
alert("oukey!!");
return("ok");
}
btw, its working like a charm! ;)
best regards and thanks to jfriend00 of course!
Check a password between 7 to 16 characters which contain only characters, numeric digits, underscore and first character must be a letter-
/^[A-Za-z]\w{7,14}$/
Check a password between 6 to 20 characters which contain at least one numeric digit, one uppercase, and one lowercase letter
/^(?=.\d)(?=.[a-z])(?=.*[A-Z]).{6,20}$/
Check a password between 7 to 15 characters which contain at least one numeric digit and a special character
/^(?=.[0-9])(?=.[!##$%^&])[a-zA-Z0-9!##$%^&]{7,15}$/
Check a password between 8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character
/^(?=.\d)(?=.[a-z])(?=.[A-Z])(?=.[^a-zA-Z0-9])(?!.*\s).{8,15}$/
I hope this will help someone. For more please check this article and this site regexr.com
A more elegant and self-contained regex to match these (common) password requirements is:
^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d^a-zA-Z0-9].{5,50}$
The elegant touch here is that you don't have to hard-code symbols such as $ # # etc.
To accept all the symbols, you are simply saying: "accept also all the not alphanumeric characters and not numbers".
Min and Max number of characters requirement
The final part of the regex {5,50} is the min and max number of characters, if the password is less than 6 or more than 50 characters entered the regex returns a non match.
I have a regex, but it's a bit tricky.
^(?:(?<Numbers>[0-9]{1})|(?<Alpha>[a-zA-Z]{1})|(?<Special>[^a-zA-Z0-9]{1})){6,50}$
Let me explain it and how to check if the tested password is correct:
There are three named groups in the regex.
1) "Numbers": will match a single number in the string.
2) "Alpha": will match a single character from "a" to "z" or "A" to "Z"
3) "Special": will match a single character not being "Alpha" or "Numbers"
Those three named groups are grouped in an alternative group, and {6,50} advises regex machine to capture at least 6 of those groups mentiond above, but not more than 50.
To ensure a correct password is entered you have to check if there is a match, and after that, if the matched groups are capture as much as you desired. I'm a C# developer and don't know, how it works in javascript, but in C# you would have to check:
match.Groups["Numbers"].Captures.Count > 1
Hopefully it works the same in javascript! Good luck!
I use this
export const validatePassword = password => {
const re = /^(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9!##$%^&*()~¥=_+}{":;'?/>.<,`\-\|\[\]]{6,50}$/
return re.test(password)
}
DEMO https://jsfiddle.net/ssuryar/bjuhkt09/
Onkeypress the function triggerred.
HTML
<form>
<input type="text" name="testpwd" id="testpwd" class="form=control" onkeyup="checksPassword(this.value)"/>
<input type="submit" value="Submit" /><br />
<span class="error_message spassword_error" style="display: none;">Enter minimum 8 chars with atleast 1 number, lower, upper & special(##$%&!-_&) char.</span>
</form>
Script
function checksPassword(password){
var pattern = /^.*(?=.{8,20})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%&!-_]).*$/;
if(!pattern.test(password)) {
$(".spassword_error").show();
}else
{
$(".spassword_error").hide();
}
}
International UTF-8
None of the solutions here allow international letters, i.e. éÉöÖæÆóÓúÚáÁ, but are mainly focused on the english alphabet.
The following regEx uses unicode, UTF-8, to recognise upper and lower case and thus, allow international characters:
// Match uppercase, lowercase, digit or #$!%*?& and make sure the length is 6 to 50 in length
const pwdFilter = /^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{6,50}$/gmu
if (!pwdFilter.test(pwd)) {
// Show error that password has to be adjusted to match criteria
}
This regEx
/^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*[\d|##$!%*?&])[\p{L}\d##$!%*?&]{6,50}$/gmu
checks if an uppercase, lowercase, digit or #$!%*?& are used in the password. It also limits the length to be 6 minimum and maximum 50 (note that the length of 😀🇺🇸🇪🇸🧑‍💻 emojis counts as more than one character in the length).
The u in the end, tells it to use UTF-8.
First, we should make the assumption that passwords are always hashed (right? always hashed, right?). That means we should not specify the exact characters allowed (as per the 4th bullet). Rather, any characters should be accepted, and then validate on minimum length and complexity (must contain a letter and a number, for example). And since it will definitely be hashed, we have no concerns over a max length, and should be able to eliminate that as a requirement.
I agree that often this won't be done as a single regex but rather a series of small regex to validate against because we may want to indicate to the user what they need to update, rather than just rejecting outright as an invalid password. Here's some options:
As discussed above - 1 number, 1 letter (upper or lower case) and min 8 char. Added a second option that disallows leading/trailing spaces (avoid potential issues with pasting with extra white space, for example).
^(?=.*\d)(?=.*[a-zA-Z]).{8,}$
^(?=.*\d)(?=.*[a-zA-Z])\S.{6,}\S$
Lastly, if you want to require 1 number and both 1 uppercase and 1 lowercase letter, something like this would work (with or without allowing leading/trailing spaces)
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\S.{6,}\S$
Lastly as requested in the original post (again, don't do this, please try and push back on the requirements!!) - 1 number, 1 letter (upper or lower case), 1 special char (in list) and min 8 char, max 50 char. Both with/without allowing leading/trailing spaces, note the min/max change to account for the 2 non-whitespace characters specified.
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$%^&*()_+]).{8,50}$
^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!##$%^&*()_+])\S.{6,48}\S$
Bonus - separated out is pretty simple, just test against each of the following and show the appropriate error in turn:
/^.{8,}$/ // at least 8 char; ( /^.{8,50}$/ if you must add a max)
/[A-Za-z]/ // one letter
/[A-Z]/ // (optional) - one uppercase letter
/[a-z]/ // (optional) - one lowercase letter
/\d/ // one number
/^\S+.*\S+$/ // (optional) first and last character are non-whitespace)
Note, in these regexes, the char set for a letter is the standard English 26 character alphabet without any accented characters. But my hope is this has enough variations so folks can adapt from here as needed.
// more secure regex password must be :
// more than 8 chars
// at least one number
// at least one special character
const PASSWORD_REGEX_3 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%^&*]).{8,}$/;

Password validation php regex

I'm new to regex.
I need to validate passwords using php with following password policy using Regex:
Passwords:
Must have minimum 8 characters
Must have 2 numbers
Symbols allowed are : ! # # $ % *
I have tried the following: /^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]$/
The following matches exactly your requirements: ^(?=.*\d.*\d)[0-9A-Za-z!##$%*]{8,}$
Online demo <<< You don't need the modifiers, they are just there for testing purposes.
Explanation
^ : match begin of string
(?=.*\d.*\d) : positive lookahead, check if there are 2 digits
[0-9A-Za-z!##$%*]{8,} : match digits, letters and !##$%* 8 or more times
$ : match end of string
I would first try and find two numbers, using non-regex (or preg_match_all('[0-9]', ...) >= 2, then validating against:
^[!##$%*a-zA-Z0-9]{8,}$
This should be faster and easier to understand. To do it using only regex sounds you need lookahead which basically scans the expression twice afaik, though I'm not sure of the PHP internals on that one.
Be prepared for a lot of complaints about passwords not being accepted. I personally have a large subset of passwords that wouldn't validate against those restrictions. Also nonsensical passwords like 12345678 would validate, or even 11111111, but not f4#f#faASvCXZr$%%zcorrecthorsebatterystaple.
if(preg_match('/[!##$%*a-zA-Z0-9]{8,}/',$password) && preg_match_all('/[0-9]/',$password) >= 2)
{
// do
}
Full Strong Password Validation With PHP
Min 8 chars long
Min One Digit
Min One Uppercase
Min One Lower Case
Min One Special Chars
/^\S*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=\S*[\W])[a-zA-Z\d]{8,}\S*$/
Demo here

How to validate phone number using PHP? [duplicate]

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Closed 9 years ago.
How to validate phone number using php
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T

Categories