register form - valid username

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pimp
Forum Newbie
Posts: 9
Joined: Sat Nov 06, 2004 10:22 am

register form - valid username

Post by pimp »

hello. i have a problem regarding validating the username from a registration form. i want the username to consist only of a...z, A...Z, and _ . i can't understand the manual for ereg, please help me by any way you can. thanks
swdev
Forum Commoner
Posts: 59
Joined: Mon Oct 25, 2004 8:04 am

Post by swdev »

I am not very good at regular expressions , but take a look at this code

Code: Select all

<?php

function ValidateUsername($UserName = '')
{
  // ^ - start at the beginning of the line
  // a-z - match any character in the range a-z i.e. all lowercase characters
  // A-Z - match any character in the range A-Z i.e. all uppercase characters
  // _ - match the underscore character
  // [...] match any character that is specified between the open and close bracket
  // * match 0 or more characters
  // $ - finish at the end of the line
  $match = '/^([a-zA-Z_])*$/';
  if (1 == preg_match ($match, $UserName) )
  {
    echo $UserName . ' is valid<br />';
    $ret = true;
  }
  else
  {
    echo $UserName . ' is <strong>invalid</strong><br />';
    $ret = false;
  }
}

// test words
ValidateUsername ('Hello_world');
ValidateUsername ('A Bad Username 99');

?>
Hope this helps
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

the shortcut would be to match on \w

http://www.regular-expressions.info/reference.html


something to train your re skillz:
http://www.samuelfullman.com/team/php/t ... ster_p.php
pimp
Forum Newbie
Posts: 9
Joined: Sat Nov 06, 2004 10:22 am

Post by pimp »

thank you for helping. timvw: i understand now the expressions but how do i use it in ereg ? if i only have 2 parameters what is the value that it's returned ?
ex: echo ([a-zA-Z],"heLLo1")
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

how do i use it in ereg
Use preg_match as shown in swdev's post.
pimp
Forum Newbie
Posts: 9
Joined: Sat Nov 06, 2004 10:22 am

Post by pimp »

ok. thanks a lot
Post Reply