Jump to content

[SOLVED] Preg_match and regex validation not working


mtscales

Recommended Posts

Basically I have the following code to validate a user's entry in a form.

 

if(preg_match('/^[\w|_|\-|@|\s\']{1,100}$/',$_POST[FormTextField])){ 
Code for good form entry
}
else{ 
Code for bad form entry
}

 

I want to allow all alphanumeric characters as well as _ - @ ' and spaces.  The script seems to work it allows all the characters I want APART FROM THE ' (single quote) character.  It also seems to disallow unwanted characters.

 

Could anyone suggest a reason why if FormTextField contains a ' my script thinks it is a bad entry?

 

I am new to regex and preg_match (and php for that matter) so may be approaching this completely the wrong way.  Any Advice much appreciated.

Link to comment
Share on other sites

You don't need the "|" character in a character class separating the values -- they're "OR" by default in a class.  Also underscore is included in the \w class.

 

Try:

/^[\w\s@\'-]{1,100}$/

 

If you're getting errors from single quotes, I suspect that magic quotes might be on and the pattern is finding [/b]\'[/b] and failing on the slash.

Link to comment
Share on other sites

Thanks a lot I used stripslashes on the String from the form (magic quotes was on) changed my pattern for preg_match to

 

"/^[\w\-@\s']{1,100}$/"

 

and it works like I want it to (just had to change some single quotes to double in my html).

 

Is it best to have magic quotes on or off?

 

Link to comment
Share on other sites

Is it best to have magic quotes on or off?

 

I prefer them off, but to keep your code portable (you don't know what server it will be running on in the future) you should check get_magic_quotes_gpc() before using stripslashes().

 

Note: You don't have to escape the hyphen if you put it at the beginning or end of a character class.

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.