preg_match user validation - php

Im trying to make a preg_match rule for user validation
to only allow a-z - A-Z - 0-9
and the characters _-=?!#:.,
without spaces
I already tried a lot of combinations but no one seems to work
This is what im trying to get:
if(preg_match('idk what to use here', 'Myusername#123?')) {
return true;
}
if(preg_match('idk what to use here', '$Hello')) {
return false;
}
if(preg_match('idk what to use here', 'Hello 123')) {
return false;
}
Anyone knows the regex for this?
Thanks :)

Use a class, but make sure to either escape the hyphen or put it as the last character, otherwise it signifies a range. Use ^ and $ to require that all input characters match the pattern:
$regex = "/^[A-Za-z0-9_=?!#:.,-]*$/";
var_dump(preg_match($regex, 'Myusername#123?'));
var_dump(preg_match($regex, '$Hello'));
var_dump(preg_match($regex, 'Hello 123'));

Related

PHP "preg_match" to check whether the text contains small characters [duplicate]

I would like to validate a string with a pattern that can only contain letters (including letters with accents). Here is the code I use and it always returns "nok".
I don't know what I am doing wrong, can you help? thanks
$string = 'é';
if(preg_match('/^[\p{L}]+$/i', $string)){
echo 'ok';
} else{
echo 'nok';
}
Add the UTF-8 modifier flag (u) to your expression:
/^\p{L}+$/ui
There is also no need to wrap \p{L} inside of a character class.
I don't know if this helps anybody that will check this question / thread later. The code below allows only letters, accents and spaces. No symbols or punctuation like .,?/>[-< etc.
<?php
$string = 'États unis and états unis';
if(preg_match('/^[a-zA-Z \p{L}]+$/ui', $string)){
echo 'ok';
} else{
echo 'nok';
}
?>
If you want to add numbers too, just add 0-9 immediately after Z like this a-zA-Z0-9
Then if you are applying this to form validation and you are scared a client/user might just hit spacebar and submit, just use:
if (trim($_POST['forminput']) == "") {... some error message ...}
to reject the submission.

PHP - Password RegEx requirements

I am trying to validate if a new user account's password is matching these criterias:
Between 8-30 characters long
Contains at least 1 lowercase letter (a-z)
Contains at least 1 uppercase letter (A-Z)
Contains at least 1 of the following special characters: _-!#*#&
I have a function like this:
function validPassword($str) {
return preg_match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_-!#*#&])[A-Za-z\d_-!#*#&]{8,30}$", $str);
}
But I am getting an error. It should return "true" for this password for example: HelloWorld123!
But instead it is returning false. Any idea what may be wrong?
if (validPassword($password) == true) {
// good password
}
You forgot to escape '-', and delimiters...
function validPassword($str) {
return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$/", $str);
}
Your regex is having errors which is why there is no match in the first place.
Change your regex to this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*#&])[A-Za-z\d_\-!#*#&]{8,30}$
Have a look at your regex in action here: https://regex101.com/r/ogPPeb/1

What will be regex for checking alphanumeric dot dash and underschore using preg_match?

I am checking username entered by user
I'm trying to validate usernames in PHP using preg_match() but I can't seem to get it working the way I want it. I require preg_match() to:
accept only letters , numbers and . - _
i.e. alphanumeric dot dash and underscore only, i tried regex from htaccess which is like this
([A-Za-z0-9.-_]+)
like this way but it doesnt seem to work, it giving false for simple alpha username.
$text = 'username';
if (preg_match('/^[A-Za-z0-9.-_]$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
How can i make it work ?
i am going to use it in function like this
//check if username is valid
function isValidUsername($str) {
return preg_match('/[^A-Za-z0-9.-_]/', $str);
}
i tried answwer in preg_match() and username but still something is wrong in the regex.
update
I am using code given by xdazz inside function like this.
//check if username is valid
function isValidUsername($str) {
if (preg_match('/^[A-Za-z0-9._-]+$/' , $str)) {
return true;
} else {
return false;
}
}
and checking it like
$text = 'username._-546_546AAA';
if (isValidUsername($text) === true) {
echo 'good';
}
else{
echo 'bad';
}
You missed the +(+ for one or more, * for zero or more), or your regex only matches a string with one char.
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
hyphen - has special meaning inside [...] that is used for range.
It should be in the beginning or in the last or escape it like ([A-Za-z0-9._-]+) otherwise it will match all the character that is in between . and _ in ASCII character set.
Read similar post Including a hyphen in a regex character bracket?
Better use \w that matches [A-Za-z0-9_]. In shorter form use [\w.-]+
What is the meaning for your last regex pattern?
Here [^..] is used for negation character set. If you uses it outside the ^[...] then it represents the start of the line/string.
[^A-Za-z0-9.-_] any character except:
'A' to 'Z',
'a' to 'z',
'0' to '9',
'.' to '_'
Just put - at the last in character class and add + after the char class to match one or more characters.
$text = 'username';
if (preg_match('/^[A-Za-z0-9._-]+$/' , $text)) {
echo 'true';
} else {
echo 'false';
}
function should be like this
function isValidUsername($str) {
return preg_match("/^[A-Za-z0-9._-]+$/", $str);
}

how to use php preg_match() to detect illegal characters when given only legal characters?

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}/

RegEx to validate usernames

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}$

Categories