I wish to validate user input based on the following requirements:
Must be alphanumeric
Longer or equal to five characters
I have succeded with the above but two of my other requirements remains:
Must have UTF8 characters åäöÅÄÖ
Must allow dot and slash
if(!(preg_match('/^\w{5,}$/', $username))) { return true; }
Can anyone help me extend this expression for my requirements?
Use unicode propeties:
if(!(preg_match('~^[\pL\pN./]{5,}$~u', $username))) { return true; }
\pL stands for any letter
\pN stands for any number.
Try this:
if(!(preg_match('/^[\w.\/]{5,}$/u', $username))) { return true; }
if(!(preg_match('/^[a-zA-Z0-9.\/]{5,}$/', $username))) { return true; }
Related
This question already has answers here:
Including a hyphen in a regex character bracket?
(6 answers)
Closed 6 years ago.
i have this function:
public static function encPasswordCheckFailed($password)
{
if (!preg_match('/[A-Z]+/', $password)){
return true;
}
if (!preg_match('/[a-z]+/', $password)){
return true;
}
if (!preg_match('/[0-9]+/', $password)){
return true;
}
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
return false;
}
and now i want to force the user to have at least 1 Uppercased Letter, 1 Lowercased Letter, 1 Number and 1 Specialcharacter.
I'm having the problem with this:
if (!preg_match('/[!##$%^&*()-+<>]+/', $password)) {
return true;
}
All other requirements work. I have only a problem with the specialcharacters.
Can someone tell me the correct pattern for these specialcharacters: !##$%^&*()-+<>
i've read some of the answers from here, here and here but they didn't help me further...
You may need to escape some special characters used by the Regex Engine. And by the way, you could as well do that in one Go as shown below. Quick-Test Here.
<?php
/*public static*/ function encPasswordCheckFailed($password) {
// THIS READS:
// IF THE PASSWORD DOES CONTAIN AN UPPER-CASE CHARACTER
// AND ALSO DOES CONTAIN A LOWER-CASE CHARACTER
// AND STILL DOES CONTAIN A NUMERIC CHARACTER
// AND EVEN MORE, DOES CONTAIN ANY OF THE SPECIFIED SPECIAL CHARACTERS
// RETURN FALSE OTHERWISE RETURN TRUE
if (preg_match('/[A-Z]+/', $password) && // CHECK FOR UPPERCASE CHARACTER
preg_match('/[a-z]+/', $password) && // AND CHECK FOR LOWERCASE CHARACTER
preg_match('/[0-9]+/', $password)&& // AND CHECK FOR NUMERIC CHARACTER
preg_match('/[\!##$%\^&\*\(\)\-\+<>]+/', $password) // AND CHECK FOR SPECIAL CHARACTER
) {
return false;
}
return true;
}
var_dump( encPasswordCheckFailed("abcd123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD123") ); //<== boolean true
var_dump( encPasswordCheckFailed("abcD1#23-") ); //<== boolean false
The dash/minus character is your issue, as when inside a character group, it denotes a character range.
You need to either:
Escape it with a backslash, so that it isn't treated as a special character:
/[!##$%^&*()\-+<>]+/
Or put it at the end of the pattern, so the PCRE engine knows it can't possibly denote a range:
/[!##$%^&*()+<>-]+/
Similarly, the caret (^) is also a special character, denoting negation when inside a character group, but because you didn't put it at the very first position inside the character group, the PCRE engine knows it has no special meaning in your case.
This will gonna work for special characters:
preg_match('/\[!##$%^&*\(\)\-+<>\]+/', $password);
If it's not working, look down:
OTHER ANSWERS:
preg_match php special characters (pmm's answer)
I have a set of characters that are allowed in a string of text. Is it possible to use preg_match to detect the existence of characters outside of the range of provided characters?
for example:
$str1 = "abcdf9"
$str2 = "abcdf#"
$str3 = "abcdfg"
legal chars = "a-z"
if (preg_match() ... ) needs to return false for '$str1' & '$str2', but 'tru' for $str3.
Will this be possible?
if(!preg_match('/[^a-z]/', $string)) { //only a-z found }
//or
if(preg_match('/[^a-z]/', $string)) {
return false; // other stuff found
} else {
return true; // only a-z found
}
See this site very usefull to deploy your regEx
http://regexr.com/
What do you need is /[a-z]/ ?
You can specify the number of chars with /[a-z]{5}/
I have a reg exp which is supposed to check if there are any illegal characters in a name. THe allowed characters are 0-9, a-z, A-Z, middlescore(-) and underscore( _ ).
This is the function
function validate_playername($playername){
if (preg_match('/^[0-9A-Z-_]$/i',$playername)) {
return true;
} else{
return false;
}
}
the function is called like this
if (validate_playername($addplayer)) {
echo "valid player Name";
} else {
echo "Invalid Player Name";
}
However when I enter a correct name like velocity28 it returns as an Invalid player name. Is my reg exp wrong?
/^[0-9A-Z-_]$/i matches only one character.
Append + to match multiple characters:
'/^[-0-9A-Z_]+$/i'
moved - to the beginning.
UPDATE
As Enissay commented, the regular expression can be simplified using \w:
'/^[-\w]+$/'
To use a literal minus sign in a character class, it must be escaped with a backslash:
function validate_playername($playername){
if (preg_match('/^[0-9A-Z\-_]$/i',$playername)) {
return true;
} else{
return false;
}
}
See http://php.net/manual/de/regexp.reference.character-classes.php for further information.
You could also move the minus sign to a position where it can't be part of character range definition, e.g. make it the first character in the character class.
I am not very good in Regular Expression, and can't seem to understand them quite well.
I am looking for a regular expression which will match and allow following strings for a username, with these conditions:
username can: start with a number or with a alphabetic letter
username can contain special chars: dots, dashes, underscores
username must be in this range: from 3 chars up to 32 chars.
alphanumeric characters in the username can be both: lowercase and uppercase
cannot contain empty spaces
Almost similar to Twitter's and Facebook username patterns.
Please help me. Thank you.
FWI: I have tried this: /^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/ - and this does not satisfy my conditions.
Try this one
^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$
this results in the php code
if (preg_match('~^[a-zA-Z0-9][a-zA-Z0-9\._-]{2,31}$~', $username) {
//do something
}
Starts with digit or alphabetic
[a-zA-Z0-9]
can contain as above plus dots, dashes and underscores
[a-zA-Z0-9._-]
and all together
[a-zA-Z0-9][a-zA-Z0-9._-]{2, 31}
try this one this is working for me in every registration form
//username Validation
var usernameRegex = /^[a-zA-Z0-9\s\[\]\.\-#']*$/i;
var username=document.getElementById('username');
if(username.value==""){
document.getElementById('lblusername').innerHTML="Username Required!";
username.focus();
return false;
}
else if(usernameRegex.test(username.value)== false)
{
document.getElementById('lblusername').innerHTML="Allow Alphanumeric Only! (E.g Demo123)";
username.focus();
return false;
}
else
{
document.getElementById('lblusername').innerHTML="";
}
Try this:
^[0-9a-zA-Z][0-9a-zA-Z\-\._]{2,31}$
I am writing a PHP validation for a user registration form. I have a function set up to validate a username which uses perl-compatible regular expressions. How can I edit it so that one of the requirements of the regular expression are AT MOST a single . or _ character, but NOT allow that character at the beginning or end of the string? So for example, things like "abc.d", "nicholas_smith", and "20z.e" would be valid, but things like "abcd.", "a_b.C", and "_nicholassmith" would all be invalid.
This is what I currently have but it does not add in the requirements about . and _ characters.
function isUsernameValid()
{
if(preg_match("/^[A-Za-z0-9_\.]*(?=.{5,20}).*$/", $this->username))
{
return true; //Username is valid format
}
return false;
}
Thank you for any help you may bring.
if (preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
// there is at most one . or _, and it's not at the beginning or end
}
You can combine this with the string length check:
function isUsernameValid() {
$length = strlen($this->username);
if (5 <= $length && $length <= 20
&& preg_match("/^[a-zA-Z0-9]+[._]?[a-zA-Z0-9]+$/", $this->username)) {
return true;
}
return false;
}
You could probably do the whole lot using just one regex, but it would be much harder to read.
You can use the following pattern, I have divided it into multiple lines to make it more understandable:
$pattern = "";
$pattern.= "%"; // Start pattern
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "[\\._]"; // Contains exactly either one "_" or one "."
$pattern.= "[a-z0-9]+"; // Some alphanumeric chars, at least one.
$pattern.= "%i"; // End pattern, optionally case-insensetive
And then you can use this pattern in your function/method:
function isUsernameValid() {
// $pattern is defined here
return preg_match($pattern, $this->username) > 0;
}
Here is a commented, tested regex which enforces the additional (unspecified but implied) length requirement of from 5 to 20 chars max:
function isUsernameValid($username) {
if (preg_match('/ # Validate User Registration.
^ # Anchor to start of string.
(?=[a-z0-9]+(?:[._][a-z0-9]+)?\z) # One inner dot or underscore max.
[a-z0-9._]{5,20} # Match from 5 to 20 valid chars.
\z # Anchor to end of string.
/ix', $username)) {
return true;
}
return false;
}
Note: No need to escape the dot inside the character class.