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
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'])) {

 

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.