Jump to content

Validating Apostrophe's with Regular Expressions


Camel

Recommended Posts

Hello Guys,

 

I am new to Php and having some problems with form validation.

 

I have a form with a  First Naame field. This field should only accept letters, dashes and apostrophes. The Regular Expression I have put together now follows:

 

$regexp_n="/[^a-zA-Z-\\s]+/i";

 

if (isset($fields[$field_name]) && !preg_match($regexp_n,  $fields[$field_name]))

       

     

          $errors[] = $error_message;

        break;

 

When I run the scripts and type words such as John, John-Smith,etc everthing works. However, when I add an apostrophe in the name (i.e. O'Reilly) it complains.

 

I would like for apostrophes to be accepted as well. Yes, I have wrapped my form fields with stripslashes() to avoid the aposrophe from being backslashes.

 

Example:

<input type="text" name="letter_field" value="<?php echo htmlentities(stripslashes(@$fields['letter_field']));?>"  size="35" maxlength="40"/>

 

 

I have tried everything and would like a little advice regarding what I'm doing wrong.

 

Thanks alot guys.

Rhodesa,

 

I have now made this modification to accept a name such as John O'Reilly. However, when I type numbers in the field along with the names, it accepts them (i.e. 22O'Reilly or John O'Reilly 333)

 

$regexp_n="/^[^a-z\-'\\s]+$/i";

 

Any suggestions. What I'm a still doing wrong? Thanks alot.

Here is the block of code again:

 

 

case "letters_only":

        if (isset($fields[$field_name]) && preg_match("/^[^a-zA-Z\'\\s]+\$/i", $fields[$field_name])  )

          $errors[] = $error_message;

        break;

 

 

This code validates names now such as John O'Reilly John Smith but when I add numbers, it accepts them too.

 

If you need more code let me know.

 

It is now working somewhat, however, when I add the apostrophe in the regular expression the compiler fires off an error in the browser. Here is the last updated code:

 

    if (isset($fields[$field_name]) && preg_match("/^[^a-zA-Z\\s']+\$/i", $fields[$field_name])  )

 

Now when I type 0'Hare it does not compalin when it should as there is a number in front of the apostrophe. Could it be a problem with the double or string quoting around the preg_match?

 

Thanks again. I would really like to solve this issue.

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.