Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate username as alphanumeric with underscores

The actual matched characters of \w depend on the locale that is being used:

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

So you should better explicitly specify what characters you want to allow:

/^[A-Za-z0-9_]+$/

This allows just alphanumeric characters and the underscore.

And if you want to allow underscore only as concatenation character and want to force that the username must start with a alphabet character:

/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/

Here's a custom function to validate the string by using the PHP ctype_alnum in conjunction with an array of allowed chars:

<?php

$str = "";
function validate_username($str) {

  // each array entry is an special char allowed
  // besides the ones from ctype_alnum
  $allowed = array(".", "-", "_");

  if ( ctype_alnum( str_replace($allowed, '', $str ) ) ) {
    return $str;
  } else {
    $str = "Invalid Username";
    return $str;
  }
}

?>

try

function validate_alphanumeric_underscore($str) 
{
    return preg_match('/^[a-zA-Z0-9_]+$/',$str);
}

Looks fine to me. Note that you make no requirement for the placement of the underscore, so "username_" and "___username" would both pass.