Home > database >  Regex function not giving expected result
Regex function not giving expected result

Time:01-27

I'm trying to validate the username according to the following rule:

No space at beginning or end, at least 2 characters, must not have the following characters: \ " ' % ; ( )

The expression that I've written in PHP is :

if (preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $this->username) || StringHelper::strlen($this->username) < 2
        || $filterInput->clean($this->username, 'TRIM') !== $this->username || StringHelper::strlen($this->username) > 150)
    {
        return false; //false will display an error message
    }

But on trying the following usernames :

  1. userName<test : accepted as userName.
  2. userName<>test: accepted as userNametest
  3. userName>test :not accepted

So it should be matching on the < and > characters and they should be in the error message

But other parts of the validation are breaking that I think. Please let me know what is wrong in the regex expression.

CodePudding user response:

Try this expression

^ |[ )"'%;()]$

reg

CodePudding user response:

Or this one:

$test=array("test>string"," test<string","abc;def","a(bc)d");

foreach($test as $t)
   echo "$t: ".preg_match("/^[^\\\"'%;()] $/",trim($t))."\n";

result:

test>string: 1
test<string: 1
abc;def: 0
a(bc)d: 0

Instead of testing for spaces at the beginning and the end I would simply trim them away!

CodePudding user response:

wouldn't it be better with a

function isValidUsername(string $name, string &$failReason=null): bool {
    if($name!==ltrim($name)){
        $failReason = "username cannot start with spaces";
        return false;
    }
    if($name!==rtrim($name)){
        $failReason = "username cannot end with spaces";
        return false;
    }
    $len = strlen($name);
    if($len < 2){
        $failReason = "username must be minimum 2 characters long";
        return false;
    }
    if($len !== ($illegalPos = strcspn($name , '\\"\'%;()'))){
        $failReason = "illegal character on position {$illegalPos}";
        return false;
    }
    $failReason = "";
    return true;
}

then you could also explain exactly what is wrong with the username... btw are you really intending to allow NULL bytes in your username? eg "a\x00b" is a valid username? i'd add \x00 to illegal characters and also do a if(!mb_check_encoding($name,'UTF-8')){$failReason="username must be UTF-8";return false;}

CodePudding user response:

check out this article, it will direct and enlighten you on how to use regex

https://support.kobotoolbox.org/restrict_responses.html

  •  Tags:  
  • Related