Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow underscore and dash with ctype_alnum()?

Tags:

regex

php

How can I add the exception of _ and - as valid characters when using ctype_alnum() ?

I have the following code:

if ( ctype_alnum ($username) ) {

  return TRUE;

} elseif (!ctype_alnum  ($username)) {
    
  $this->form_validation->set_message(
    '_check_username',
    'Invalid username! Alphanumerics only.'
  );

  return FALSE;
}
like image 573
Tristan Avatar asked Aug 26 '11 00:08

Tristan


3 Answers

Since ctype_alnum only validates alpha numeric character, Try this:

$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
} 
like image 79
Book Of Zeus Avatar answered Nov 11 '22 01:11

Book Of Zeus


Use preg_match instead, maybe?

if(preg_match("/^[a-zA-Z0-9_\-]+$/", $username)) {
    return true;
} else {
    $this->form_validation->set_message('_check_username', 'Invalid username! Alphanumerics only.');
}
like image 5
Ry- Avatar answered Nov 11 '22 01:11

Ry-


Here is how to use ctype_alnum AND have exceptions, in this case I also allow hyphens ( OR statement).

$oldString = $input_code;
$newString = '';
$strLen = mb_strlen($oldString);
for ($x = 0; $x < $strLen; $x++) 
   {
     $singleChar = mb_substr($oldString, $x, 1);
     if (ctype_alnum($singleChar) OR ($singleChar == '-'))
        {
          $newString = $newString . $singleChar;
        }
   }
$input_code = strtoupper($newString);
like image 2
RedKeyCode Avatar answered Nov 11 '22 01:11

RedKeyCode