PHP preg_match on text not working - php

This php code is not catching numeric characters or symbols as it should.
$firstname = check_input($_POST['firstname'], "Please enter your first name");
$firstname = ucwords($firstname);
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
show_error("Name should have only alpha characters and white space");
}
For example, the results should be Geronimo. If ge5on*mo is entered, that's what gets returned.
Any suggestions?

Well, no full test cases in your example. So I will try to walk blindly in the dark. At first your expression is flawed, because it can capture just empty spaces without any name. Second - it doesn't captures unicode characters. I would start with such expression for name capture :
^(?:\p{Lu}\p{Ll}+[-\h]?){1,}$
Explanation:
^(?:
\p{Lu} // first letter in name must be in upper-case
\p{Ll}+ // after that goes at least 1 non-upper case letter
[-\h]? // we allow separators between names
){1,} // human can have multiple names (at least 1)
$

Related

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,}$/;

Unique regex for name validation

I want to check is the name valid with regex PHP, but i need a unique regex that allows:
Letters (upper and lowercase)
Spaces (max 2)
But there can't be a space after space..
For example:
Name -> Dennis Unge Shishic (valid)
Name -> Denis(space)(space) (not valid)
Hope you guys understand me, thank you :)
First, it's worth mentioning that having such restrictive rules for the names of persons is a very bad idea. However, if you must, a simple character class like this will limit you to just uppercase and lowercase English letters:
[A-Za-z]
To match one or more, you need to add a + after it. So, this will match the first part of the name:
[A-Za-z]+
To capture a second name, you just need to do the same thing preceded by a space, so something like this will capture two names:
[A-Za-z]+ [A-Za-z]+
To make the second name optional, you need to surround it by parentheses and add a ? after it, like this:
[A-Za-z]+( [A-Za-z]+)?
And to add a third name, you just need to do it again:
[A-Za-z]+( [A-Za-z]+)? [A-Za-z]+
Or, you could specify that the latter names can repeat between 1 and 2 times, like this:
[A-Za-z]+( [A-Za-z]+){1,2}
To make the resulting code easy to understand and maintain, you could use two Regex. One checking (by requiring it to be true) that only the allowed characters are used ^[a-zA-Z ]+$ and then another one, checking (by requiring it to be false) that there are no two (or more) adjacent spaces ( ){2,}
Try following working code:
Change input to whatever you want to test and see correct validation result printed
<?php
$input_line = "Abhishek Gupta";
preg_match("/[a-zA-Z ]+/", $input_line, $nameMatch);
preg_match("/\s{2,}/", $input_line, $multiSpace);
var_dump($nameMatch);
var_dump($multiSpace);
if(count($nameMatch)>0){
if(count($multiSpace)>0){
echo "Invalid Name Multispace";
}
else{
echo "Valid Name";
}
}
else{
echo "Invalid Name";
}
?>
A regex for one to three words consisting of only Unicode letters in PHP looks like
/^\p{L}+(?:\h\p{L}+){1,2}\z/u
Description:
^ - string start
\p{L}+ - one or more Unicode letters
(?:\h\p{L}+){1,2} - one or two sequences of a horizontal whitespace followed with one or more Unicode letters
\z - end of string, even disallowing trailing newline that a dollar anchor allows.

PHP How do I get this preg_match Regex to work?

I have to have a regular expression that contains at least one lowercase letter, uppercase letter, number, and symbol (non letter or number). I must also contain no spaces and must be between 8 and 16 characters long. I must use the 0-9a-zA-z Expression. I cannot use any other to represent the letters and numbers.
I have run into a few problems which I hope you guys can help me with. I will seperate the issues with line.
1) Quantifier not working
<?php
$Password = "Fondulious16";
echo preg_match("/[0-9a-zA-Z]{8,16}[^\s]/", $Password);
?>
Now, It does return 0 if i change the password to go below 8 chacters. But it still returns a 1 if I go above 16 characters.
2) Requirements not working
If I change the brackets to parenthesis it always returns 0 and I can remove the capital letter. So i need to make it to where It will require a capital, lower case, and number. I've tried adding in the + symbol but to no avail:
<?php
$Password = "Fondulious16";
echo preg_match("/[0-9+a-z+A-Z+]{8,16}[^\s]/", $Password);
?>
This did nothing, and nothing changed when I changed the password to something like "fondulious".
<?php
$Password = "Fondulious16";
echo preg_match("/(0-9a-zA-Z){8,16}[^\s]/", $Password);
?>
This always returns 0.
Thanks in advance for any help.
Your problem in both cases is the fact that [^\s] is essentially the same as \S; in short: Anything but a space character.
So this last part of the expression will match anything as long as there is indeed at least some character (i.e. not the end of the string).
Also you can't use the + quantifier within one selection/range ([...]). It's just a normal character in there and by default the quantifier following will be able to pick any valid character as often as necessary (there's no easy way to force the elements to be unique anyway).
So, to fix your problem, you should use the following regular expression:
<?php
$password = "Fondulious16";
echo preg_match('/^\w{8,16}$/', $password);
?>
Here's a short explanation of the elements:
^ will match the beginning of the string.
\w will match any alphanumerical character plus underscores (essentially [a-z0-9_], but case-insensitive).
{8,16} is a quantifier "8 to 16 times" as you used it.
$ will match the end of the string.
If you don't want underscores to be valid, you can use the following variant.
<?php
$password = "Fondulious16";
echo preg_match('/^[0-9a-z]{8,16}$/i', $password);
?>
You might have noticed that I didn't list uppercase characters. Instead, I've used the modifier i after the trailing delimiter (/i) which will tell the algorithm to ignore the case of all characters when trying to match them.
Although it's important to note that this check will not force the user to use lowercase and uppercase characters as well as numbers. It will only check whether the user used any other characters (like punctuation or spaces) as well as the length!
To force the user to use all those things in addition, you can use the following check:
<?php
$password = "Fondulious16";
echo preg_match('/[A-Z]/', $password) // at least one uppercase character
&& preg_match('/[a-z]/', $password) // at least one lowercase character
&& preg_match('/\d/', $password); // at least one number
?>
If you'd like to do these checks and you want to verify the length as well, then you can use the following expression to look for illegal characters (and a simple string length check to ensure the length is fine):
<?php
$password = "Fondulious16";
echo ($pwlen = strlen($password)) >= 8 && $pwlen <= 16 // has the proper length
&& preg_match('/[A-Z]/', $password) // at least one uppercase character
&& preg_match('/[a-z]/', $password) // at least one lowercase character
&& preg_match('/\d/', $password) // at least one number
&& !preg_match('/[^a-z\d]/i', $password); // no forbidden character
?>
Please look at the below
example
if (!preg_match('/([a-z]{1,})/', $value)) {
// atleast one lowercase letter
}
if (!preg_match('/([A-Z]{1,})/', $value)) {
// atleast one uppercase letter
}
if (!preg_match('/([\d]{1,})/', $value)) {
// altelast one digit
}
if (strlen($value) < 8) {
// atleast 8 characters length
}

How to use preg_match to match everything except numbers in PHP?

Here is my code:
//Validate names have correct characters
if (preg_match("/^[a-zA-Z\s-]+$/i", $_POST['first']) == 0) {
echo '<p class="error">Your first name must only include letters,
dashes, or spaces.</p>';
$okay = FALSE;
}
if(preg_match("/^[a-zA-Z\s-]+$/i", $_POST['last']) == 0) {
echo '<p class="error">Your last name must only include letters,
dashes, or spaces.</p>';
$okay = FALSE;
}
How do I modify this code so that it accepts everything except numbers?
Vedran was most correct. The \d means digits, and the capital \D means NOT digits. So you would have:
if (preg_match("/\d/i", $_POST['first']) > 0) {
echo '<p class="error">Digits are not allowed, please re-enter.</p>';
$okay = FALSE;
}
The above means... If you find any digit... do your error. aka: allow everything except digits.
HOWEVER... I believe you need to re-think your idea to allow "Everything Except digits." You typically don't want the user to enter Quotes or Special ACII Characters, but it appears you want them to be able to enter -!##$%^&*()_+=|}{\][:;<>?,./~
That seems like a long list, but compared to the complete list of possible characters, it isn't that long. So even though it seems like more work, you might want to do that:
if (preg_match("/[^-~`!##$%^&*()+={}|[]\:;<>?,.\w]/i", $_POST['first']) > 0) {
echo '<p class="error">ASCII and Quotes are not accepted, please re-enter.</p>';
$okay = FALSE;
}
Neither one of these have the Beginning/End-Line special characters, because you are looking anywhere in the string for any occurance of (or not of) these checks.
I changed the comparison operator to (if greater than) because we aren't looking for the lack of something required to throw an error anymore, we are looking for the existence of something bad to throw an error.
Also, I took the underscore out of the last regex there... because the Word Character (\w) includes digits, letters, and underscores. Lastly, the dash in the character-class has to be either FIRST or LAST in the list, or it sometimes throws errors or is accidentally mistaken as a range character.
preg_match("/^[^0-9]*$/", $string)
accepts everything but numbers.

Regular expression with php

$pattern="/[a-z]*[a-z]*/i";
if(!preg_match($pattern, $value)){
$this->error_name="The name should contain at least two letters.";
}
I am trying to check if the user types his name with at least two letters. So basically, he cant enter his name as such 111111111111.. it must have two letters.
The regular expression that I wrote doesnt work..why?
You can use:
$pattern="/^[a-z]{2,}$/i";
This will ensure that the name has only letters and there are at least 2 letters in the name.
Edit:
Looks like you want the name to contain at least two letter and can contain other non-letters as well:
$pattern="/^.*[a-z].*[a-z].*$/i";
Try this (your code modified):
$pattern="/^[a-z]{2}.*/i";
if(!preg_match($pattern, $value)){
$this->error_name="The name should contain at least two letters.";
}
Returns true when at least two alphabets are used in a string:
preg_match_all('/[a-z]/', $str, $m) >= 2;
$pattern="/[a-z].*[a-z]/i";
if(!preg_match($pattern, $value)){
$this->error_name="The name should contain at least two letters.";
}
Your code didn't work because * means zero or more times, so it would also match none or one character.
$pattern="/^([a-z]{2})|([a-z].*[0-9].*[a-z].*).*/i";
I think the answer should be the one above.. your answers gave me a clue..
now it will match also those names:
a1111111111111a

Categories