Jump to content

[SOLVED] Trying to exclude everything but letters, nums, but spaces...


Jessica

Recommended Posts

I want to allow only letters, numbers, and the . and _ character - nothing else, no spaces, no $!, etc. This is what I have.

[code]if(preg_match("/[^A-Za-z0-9_\.]+$/", $this->username)){
    $msg = "Please use only letters, numbers, and the following characters: _ and .";
}else{
    $msg = "Username OK!";
}[/code]

It works great when a user enters !@#$% etc, but when a user enters spaces in between two words, IE: john doe, it says Username OK. If they enter a space and another unallowed character it gives the error, but not if it's just two words with space. What is wrong with my regexp?
Link to comment
Share on other sites

Jesi,

What you've got there looks good. Just a few minor tweaks, I'd add:
[code]if(!preg_match('/^[A-Za-z0-9_.]+$/', $this->username)){
  $msg = "Please use only letters, numbers, and the following characters: _ and .";
}else{
  $msg = "Username OK!";
}
[/code]
I usually use a negated match (!preg_match(...)) instead of negated character classes ([^...]) in this situation. It'll work either way, just makes it easier to debug later I think (just my opinion). You sometimes run into problems with portability when you use negated classes (unicode characters start sneaking in, it gets ugly).

Two things: you don't need to escape the '.' (dot) character inside character classes. All I did was add the '^' (beginning of line/string) anchor to the start of it! That way it'll require the engine to match one of those characters in the class from the start all the way to the '$' (end of string position). The problem you had with the leading space was because the engine would fail there and exclude that from the match since it was only anchored to the end of the string.

Enjoy!
Link to comment
Share on other sites

Thanks! I am not sure why I was escaping the . - this is the first regexp I have written and despite reading a ton of tutorials and a quick reference book, I still just can't get my mind around it.

It works beautifully now, thanks a ton!
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.