if(!preg_match("/[a-zA-Z'-]/",$First)) { die ("invalid first name");}
the above only flags input as invalid when the field is all numeric. combinations of letters and numbers pass ok. Some help here for a newby please. thanks.
if(!preg_match("/[a-zA-Z'-]/",$First)) { die ("invalid first name");}
the above only flags input as invalid when the field is all numeric. combinations of letters and numbers pass ok. Some help here for a newby please. thanks.
Try:
if(!preg_match("/^[a-zA-Z'-]+$/",$First)) { die ("invalid first name");}
The ^
matches the beginning of the string, the $
matches the end of the string and +
after a character group means "one or more" matching characters.
You're only matching a single character. You need to add a wildcard like +
(1 or more). Also you're matching anywhere in the string. You need to add anchors (^
for start of string, $
for end of string) to make sure there are no invalid characters.
if (!preg_match("/^[a-zA-Z'-]+$/", $First)) { die ("invalid first name");}
Alternatively you can look for a non-matching character:
if (preg_match("/[^a-zA-Z'-]/", $First)) { die ("invalid first name");}
The ^
inside the square brackets here means "any character that is NOT one of these".
In this case better to look for invalid characters than to try and match all of the characters, once a single invalid character appears, the search can quit and return failure. This is more efficient than always scanning the whole string.
if (preg_match("/[^A-Za-z'-]/", $First)) { die ("invalid first name"); }
the ^ inside the set [] makes it match everything not in the set. and since the string is invalid if we have even one invalid character, there is no need for the set to have a repetition operator.
Even better would be a more helpful error message
if (preg_match("/[^A-Za-z'-]/", $First, $Inv)) { die ("{$Inv[0]} not allowed in first name"); }