I would like to accept only small and capital letters from the user.
I tried the below code, it echoes the invalid character message but doesn\'t work. I mean it doe
The general idea of checking for characters that don't match the [a-zA-Z]
pattern is a good one.
However, the "not" part of your if
condition is in the wrong place if you want this to work. What you've got now just makes sure that any single character in fname
is an upper- or lower-case Latin letter.
You want to push the "not" part of the logic into the pattern:
if (preg_match('/[^a-zA-Z]/', $fname)) {
This checks if any character in fname
is not a Latin letter, which is what you're trying to do.
Edit: Your new update has a different test that also works (it appears to be from sourcecode's updated answer, but you've got several tests from the different answers here that will work equally well). But, your updated post makes it clear that your problem isn't really with the pattern for testing the name.
Your code looks like this:
if (/* invalid fname */) {
echo "Invalid characters";
}
if (/* empty fname */) {
echo ' First name is required';
}
else {
/* insert into database */
}
That else
clause only depends on the the if
that comes immediately before it: the check whether fname
is empty. In other words, regardless of the result of your check against the characters of fname
, you insert it into the database whenever it's not empty.
One easy way to fix this is to just change your second if
to an elseif
. This will chain all three conditionals together, so the final else
block will only occur if both of the earlier conditionals that print error messages weren't triggered.
if (/* empty fname */) {
echo 'First name is required.';
}
elseif (/* invalid fname */) {
echo 'Invalid characters';
}
else {
/* insert into database */
}