Jump to content

White Spaces removing Usernames


zimmo

Recommended Posts

My application is gaining speed now and not far from completion. I am just going through the app and finding things wrong that I need to correct, with the first one being NOT allowing spaces when the user creates their username.

 

I have never done this before. I currently have a function that checks to see if the username exists, and return valid or not and echo to the form to tell the user.

 

What I need to do now is not allow them to use white spaces in the username or password. I wonder if someone knows or can help me get this part right.

 

Here is the error check part of the username:

	if ( empty($username) ) {
	$error['username_error'] = '<div class="formerror">Please enter your username</div>';
	}
	elseif (!validUsername ($username) ) {
	$error['username_error'] = '<div class="formerror">Username Taken please choose another.</div>';
	}

 

The function in the elseif statement is called via the include at the top of the page. It is a simple function to query the database to see if the username is taken. How could I extend this to not allow white spaces, once I sort this I know I can finish the rest that are the same as this.

Link to comment
Share on other sites

I don't know why websites choose to not allow a space in the user name.  A space is just a character, after all, and (IMHO) should be valid.  But if you want to disallow say, 'David A M' (see the spaces), then you can use strpos().  Although you might want to consider adding another function (or including it in your existing function - which would mean you would have to change the error message a little.  If you create a new function, say "validCharsUsername()" then if you later decide to not allow other characters, you change the function instead of adding another strpos() everywhere that you do the check.

** Untested code **

if ( empty($username) ) {
  $error['username_error'] = '<div class="formerror">Please enter your username</div>';
}
// Add these lines
elseif (strpos($username, ' ') !== false) {
  $error['username_error'] = '<div class="formerror">Invalid characters in username.</div>';
}
elseif (!validUsername ($username) ) {
  $error['username_error'] = '<div class="formerror">Username Taken please choose another.</div>';
}

 

another way to accomplish this is to use str_replace().  Replace all unwanted characters with something (or nothing) and compare the result with the original string.  If they match, it's OK, if they don't, it's invalid.

if (str_replace(array(' ', '<', '>'), '', $username) != $username) {
  // Invalid characters in username
}

Link to comment
Share on other sites

Hi David,

 

The reason I am doing this, is to stop people from forgetting, as alot of users tend to either put 2 spaces etc.. and then say its not working.. so trying to ease the process. Thanks for that, I can understand how it works etc.. now.

 

Can I extend this to not allow other characters?

If I create the function and use that (better idea as you say) and call that function.

 

Also, another note on functions, can you include more than one function on a php file? so I dont have to reference lots of functions on different pages?

 

 

Link to comment
Share on other sites

Ahh!  Good point!  I had not thought about that (more than one space side by side), I can see where visually that would be confusing.

 

Yes, you can put more than one function in a php file.  Then include that file on each page that needs it.  I try to combine common functions (used on lots of pages) in one file (funcCommon.php).  Functions that are only used on a couple of pages go into separate files (say funcUsers.php, funcProd.php) then I only include the file(s)  I need in the pages I need them.

 

Yes you can extend to handle multiple characters. 

function validUsernameChars($username) {
  if ( (strpos($username, ' ') !== false) 
   or  (strpos($username, '<') !== false) 
   or  (strpos($username, '>') !== false)  ) {
    return false;
  } else {
    return true;
  }
}

 

This could get tedious and look ugly if there are lots of characters you don't want.  An easier way might be:

function validUsernameChars($username) {
  $bad = array(' ', '<', '>');

  if (str_replace($bad, '#', $username) != $username) {
    return false;
  } else {
    return true;
  }
}

The idea here is that if I replace bad characters with anything (or nothing) then the result is not equal to the original, so there were some bad characters in there.

 

Using a function instead of putting the check directly into your code gives you more flexibility.  Even if you only do this in one place.  If you later decide that all user names MUST have atleast ONE digit, you add that check in the function and you are done.

 

Link to comment
Share on other sites

I almost always use preg_match for this type of thing:

function validate_username( $val ) {
    $errors = array();
    if( ! strlen( trim( $val ) ) ) {
        $errors[] = 'Username is required.';
    }
    if( ! preg_match( '/^[a-z][a-z0-9_]$/i', $val ) ) {
        $errors[] = 'Username starts with a letter and contains a combination of letters, digits, and underscores only.';
    }
    return $errors;
}

 

<?php
$username = array_key_exists( 'username', $_POST ) ? $_POST['username'] : '';
$username_errs = validate_username( $username );
if( count( $username_errs ) > 0 ) {
    echo '<ul><li>' . implode( '</li><li>', $username_errs ) . '</li></ul>';
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.