Jump to content

[SOLVED] form validation


CincoPistolero

Recommended Posts

I want a field to be letters only "-" and "_". No special characters. No Numbers. I have the javascript form validation working, however, I also want PHP form validation set. Below is what I have coded for checking to make sure the field only contains the characters mentioned above. Now, when I enter just letters in the field, it gives me the error I have coded. Letters should work, but are failing.

// Check for numbers in first name
	if (!eregi('^[a-zA-Z_-]$',$_POST['fname'])) {
		die('<div id=error><table cellpadding="0" cellspacing="0" border="0" align="center" bgcolor="#ffffff">
      <tr>
        <td><br><br>No numbers or special characters allowed in first name.<br><a href="javascript:history.back()">Back</a><br><br></td>
      </tr>

    </table></div>');
}

Link to comment
https://forums.phpfreaks.com/topic/180173-solved-form-validation/
Share on other sites

a character class only matches against 1 character, and you have start of string and end of string anchors wrapped around it, so it will fail if you have more than 1 character entered.  You need to add a quantifier to it.  Also, eregi is deprecated, use preg_match instead.

 

     if (!preg_match('^[a-zA-Z_-]+$',$_POST['fname'])) {

 

the + is the quantifier. It means 1 or more of what's inside that character class.  If you want it to be a specific amount, like only 5-10 characters, do this instead:

 

     if (!preg_match('^[a-zA-Z_-]{5,10}$',$_POST['fname'])) {

 

I now have it like this

if (!preg_match('^[a-zA-Z_-]+$',$_POST['fname'])) {

 

it still fails with normal text, and I get this error

 

Warning: preg_match() [function.preg-match]: No ending delimiter '^' found in /home/pastwork/public_html/empl/empInfo.php on line 302

Archived

This topic is now archived and is closed to further replies.

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