I’d like to get some help regarding PHP.
Let’s say I have a string ($fullname).
I want to validate that it’s in the form of “Firstname_Lastname”.
For example, make sure that it’s “Nathan_Phillips” and not “Nathan Phillips” or “Nathan122” etc.
Can you guys help me with the function?
Thanks in advance! 🙂
———— EDIT ————-
Thank you guys! Managed to do that. Also added the numbers filter. Here’s the function:
function isValidName($name)
{
if (strcspn($name, '0123456789') != strlen($name))
return FALSE;
$name = str_replace(" ", "", $name);
$result = explode("_", $name);
if(count($result) == 2)
return TRUE;
else
return FALSE;
}
Usage example:
if(isValidName("Test_Test") == TRUE)
echo "Valid name.";
else
echo "Invalid name.";
Thanks again!
Maybe try something like this:
This will accept a string containing 2-50 alphabetic characters, followed by an underscore, followed by 2-50 alphabetic characters.
I’m not the best with regex, so I invite corrections if anyone sees a flaw.
If you have special characters (è, í, etc.), the regex I gave probably won’t accept it. Also, it won’t accept names like O’Reilly or hyphenated names. See this:
Regex for names
I’ll let you track down all the exceptions to the regex for names, but I definitely think regex is the way to go.