Jump to content

having trouble with this preg_match code


pioneerx01

Recommended Posts

I am trying to give users error if they type in the name field anything but a-z, dash or minus, quote. If they enter a space (Dr Name) it will give them error as well. Here is the code I use, but always something, wither it lets spaces by or it does not let ' by:

 

if ((preg_match ('%[^a-z\'\-]%', $_POST['name'])) and ($_POST['control'] == 'yes'))
echo "error text";

Link to comment
Share on other sites

First off, I would always trim() the user input before doing any validation on it. But, I see nothing wrong with your expression. I ran several tests - using JUST the regex test - and they all came out as expected based upon the results you want. So, I think there are one of two problems:

 

1. You are doing TWO validations in that if() statement. base upon that logic you will only get an error IF the input does not meet the parameters AND "$_POST['control'] == 'yes'". So, if the user enters invalid text but $_POST['control'] does not equal "yes" then the validation will pass.

 

2. Your server might have magic quotes enabled. If so, the single quote marks will be escaped in the post data. Either disable magic quotes (which you should, if you can) or strip them out at run-time.

 

See the following pages:

http://us3.php.net/manual/en/security.magicquotes.php

http://us3.php.net/manual/en/security.magicquotes.disabling.php

 

Here was my test script and the results:

$testvalues = array("abc", "a-b-c", "a'b'c", "a b c", "a567", "a,b,c", "  a  ", "'''''", "-----");

foreach($testvalues as $value)
{
    echo "<br>[$value] : ";
    echo (preg_match ('%[^a-z\'\-]%', $value)) ? 'Error' : 'OK';
}

 

[abc] : OK
[a-b-c] : OK
[a'b'c] : OK
[a b c] : Error
[a567] : Error
[a,b,c] : Error
[ a ] : Error
['''''] : OK
[-----] : OK

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.