pioneerx01 Posted July 16, 2011 Share Posted July 16, 2011 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"; Quote Link to comment https://forums.phpfreaks.com/topic/242102-having-trouble-with-this-preg_match-code/ Share on other sites More sharing options...
Psycho Posted July 16, 2011 Share Posted July 16, 2011 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 Quote Link to comment https://forums.phpfreaks.com/topic/242102-having-trouble-with-this-preg_match-code/#findComment-1243332 Share on other sites More sharing options...
.josh Posted July 16, 2011 Share Posted July 16, 2011 Also, with your "Dr Adam" example, you said the problem is the space. What about capitalization, is that allowed? Your regex currently only matches lowercase letters. You need to add the "i" modifier to your regex if you want it to be case-insensitive. Quote Link to comment https://forums.phpfreaks.com/topic/242102-having-trouble-with-this-preg_match-code/#findComment-1243473 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.