Jump to content

Alphanumerical username with underscores and spaces


Brandon Jaeger

Recommended Posts

Okay, so that worked before I integrated it within a function.

Here's my test code:
[code]<?php
if(isset($_POST["submit"]))
echo username_valid_test($_POST["username"]);

echo "<br \>";
echo "<form method=\"post\" action=\"" . $_SERVER["PHP_SELF"] . "\">";
echo "<input type=\"text\" name=\"username\">";
echo "<br \><input type=\"submit\" name=\"submit\">";
echo "</form>";

function username_valid_test($username)
{
$len = strlen($username);

if($username{0} == ' ' OR $username{0} == '_')
return $username . " - Error #1";
elseif(!eregi("[^a-zA-Z0-9 _]{3,16}" , $username))
return $username . " - Error #2";
elseif(strpos($username , "  ") !== FALSE)
return $username . " - Error #3";
elseif($username{$len - 1} == '_' OR $username{$len - 1} == ' ')
return $username . " - Error #4";

return $username . " valid";
}
?>[/code]
- and here's the URL for the page that contains that exact code above: http://ghw-amxx.com/test/username_regex.php

In the past I've experienced problems with $_POST data and regex, but I don't think that's the case here. Also, it doesn't work without the [b]{3,16}[/b] part either.

---brandon
eregi doesn't like me :|

I edited a pattern and I got it working. Here's the code for anyone for future reference:
[code]<?php
if(isset($_POST["submit"]))
echo username_valid_test($_POST["username"]) . "<br \>";

echo "<form action=\"" . $_SERVER["PHP_SELF"] . "\" method=\"post\">";
echo "<input type=\"text\" name=\"username\">";
echo "<br \><input type=\"submit\" name=\"submit\">";
echo "</form>";

function username_valid_test($username)
{
$len = strlen($username);

if(!preg_match("/^[a-zA-Z0-9 _]*$/" , $username)) {
return $username . " - Error #1";
}
elseif($username{0} == ' ' OR $username{0} == '_') {
return $username . " - Error #2";
}
elseif($username{$len - 1} == '_' OR $username{$len - 1} == ' ') {
return $username . " - Error #3";
}
elseif(strpos($username , "  ") !== FALSE) {
return $username . " - Error #4";
}

return $username . " valid";
}
?>[/code]
you don't have to escape underscores and dashes if they are the leading characters in an expression.
you can also use the [b]i[/b] modifier to make expressions case insensitive

[code]
'/[^a-zA-Z0-9\_\-]/'
[/code]
is equivalent to
[code]
'/[^-_a-zA-Z0-9]/'
[/code]
which is, in turn, equivalent to
[code]
'/[^-_a-z0-9]/i'
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.