PHP splitting first name, and last name

I am sure this is pretty simple, but I am having a hard time. Maybe because it is because I cant focus with being drained from work every time I sit down to do this. I have a text input, and the user is going to enter their name. Customers will enter it last name first, and then first name. THe last name needs at least two characters, and first name needs one. There also needs to be a comma in between the names, if not then I have to display an error message.

index.php

<?php
require_once('validator.php');

$name = '';
$ip_address = '';
$phone = '';
$num = '';

$name_error = '';
$ip_address_error = '';
$phone_error = '';
$num_error = '';

if (isset($_POST['name']))
$name = $_POST['name'];

if (isset($_POST['ip']))
$ip_address = $_POST['ip'];

if (isset($_POST['phone']))
$phone = $_POST['phone'];

if (isset($_POST['num']))
$num = $_POST['num'];

$name_error = Biggs_validator\stringValid($name, 4, );

validator.php

<?php
namespace Biggs_validator;

use Exception;

function stringValid($val, $val2, $len, $len2){
if (strlen($val) < $len)
return 'Last name must be at least ' . $len . ' characters.';
else if($val2 < $len2)
return 'First name must be at least ' . $len2 . 'characters';
else
return '';

}

My inital though was to pass in both first name, and last name but then I am not sure how to make sure there is a comma between the two. Its been a while since I have done any real coding, so I am trying to get back in it

I would probably use 2 text inputs. One for the first name and the other for the last name. After validation join the 2 with a comma.

If it needs to be one input field you could check for the comma first, then split before the validation.
Something like this

if ( strpos($name, ",") {
 $last= substr($name, 0  ",");
 $first= substr($name, strpos($name, ",') + 1 , strlen($name);
$name_error = Biggs_validator\stringValid($last, $first, 2, 1);
} else {
$name_error = "comma required";
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.