开发者

PHP: form validation "Full name"

Right now i have this for full name:

if(empty($_POST['full_name']) || strlen($_POST['full_name']) < 4)
{
$errormessage[] = "ERRO开发者_StackOverflowR.\n";
}

How can i make a validation for full name, so the entered name should contain space?

So like if person enter:

John Andersson

Its ok, but if he enter:

JohnAndersson

its not ok, error. So you would need a "space" in your fullname.


Like this:

if (strpos(trim($_POST['full_name']), ' ') !== false){
  // user has specified first and last name
}
elseif (strpos(trim($_POST['full_name']), ' ') !== true){
  // user has specified a single name
}

You need to enter the trim function to check for bad names such as:

  • Justin Alba[space]
  • [space]Justin Alba
  • Justin[space]
  • [space]Justin


What you could do is split the string then check then split string parts.

$nameSplit = explode(' ', $name);

if(count($nameSplit) < 2)
{

//Only one name given

}
else
{

  $firstName = trim($nameSplit[0]);
  $secondName = trim($nameSplit[1]);

  if($secondName == '')
  {

    //No second name given

  }

}


You could possibly have two fields, one for first name and one for surname.

I assume you don't want people with one name to fill in your form so you'd exclude Bono, Eminem, Prince, Sting, Bjork, Enya and a few others.


You can do a test like:

$fullName = 'JohnAndersson';

if ( ucfirst(strtolower($fullName)) != ucfirst($fullName) ) {
    echo 'It is not valid';
}

ucfirst(strtolower($fullName)) will convert your string to Johnandersson and it is not equals to JohnAndersson so it should contains a space.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜