How to validate a form field in php?

  • Thread starter Thread starter blueshadowpt
  • Start date Start date
B

blueshadowpt

Guest
I've a guestbook that tries to validate a field "name" with this code:
} elseif (empty($c['name']) || !ereg("^[A-Za-z' -]*$", $c['name']) || strlen($c['name']) > 12) {
$error_msg .= "Name is a invalid: must not be blank, must have no special characters, must not exceed 12 characters.";
But what I want is to allow me to add a name in my language for example José. The code above doesn't allow it cause it's "erroring" the name. I know I could remove the validation intirely but that would allow 12 characters and an empty field.

Can anyone help me out??
The code in question comes from bellabook guestbook the file in question is sign.php but I can't even understand how it should be to accept accentuated characters like José or João.
Where should I put the code Deren proprosed?
I'm sorry guys but I'm a total noob on php and my poor English is in the way for trying to find the solution.
 
Strip certain characters from the string before you check it.

$string = 'XYZ';

if (eregi('X', $string)) {

$string = str_replace('X,'',$string);

}

Replace the string with something so you can add the character in afterwards though :) Some long combination that noone can guess, but make sure to increase the length limit by the length of that string - 1 (the 1 being the one you removed)
 
Hi,
You can try this..

/* First you need to remove any special characters you wish to keep, The new string (without the desired special characters) we will call '$split'. Let's say we want to allow ' - and spaces: */

$c['name'] = "José-' ";
$split = implode(preg_split('/[\s\'-]+/', $c['name']));

/* Now test on $c['name'] and also $split: */

} elseif (empty($c['name']) || preg_match('/[\W]/', $split) || strlen($c['name']) > 12) {
$error_msg .= "Name is a invalid: must not be blank, must have no special characters, must not exceed 12 characters.";

/* preg_match('/[\W]/', $split) tests '$split' for any non-word characters. */

I hope this helps!
 
Hi,
You can try this..

/* First you need to remove any special characters you wish to keep, The new string (without the desired special characters) we will call '$split'. Let's say we want to allow ' - and spaces: */

$c['name'] = "José-' ";
$split = implode(preg_split('/[\s\'-]+/', $c['name']));

/* Now test on $c['name'] and also $split: */

} elseif (empty($c['name']) || preg_match('/[\W]/', $split) || strlen($c['name']) > 12) {
$error_msg .= "Name is a invalid: must not be blank, must have no special characters, must not exceed 12 characters.";

/* preg_match('/[\W]/', $split) tests '$split' for any non-word characters. */

I hope this helps!
 
Back
Top