italoestrada's avatar

Validate full name

Is there a way to actually validate a full name?:

Example:

If i do this:


  request()->validate(
      [
        'fullname' => ['required','alpha']
      ]
)


And the name is Edison Tyler the validation fails because the space.

A full name should be:

  • At least two words
  • No numbers
  • Any latin o special character used in names.

But i cant find anything that helps.

0 likes
3 replies
thanhtrungit's avatar

@italoestrada you try use create a custom rule with regex /^[a-zA-Z]+(?:\s[a-zA-Z]+)+$/

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class FullnameRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if(preg_match('/^[a-zA-Z]+(?:\s[a-zA-Z]+)+$/', $value)){
            return true;
        }else {
            return false;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

FormRequest use:

use App\Rules\FullnameRule;
request()->validate(
      [
        'fullname' => ['required','alpha',new FullnameRule()]
      ]
)
3 likes
Talinon's avatar

You could make a custom rule, or use a regular expression.

Just be careful, because something like this is actually more complex than what you might initially think. You are assuming that all people use the same naming structure - but they don't.

Here are some thing to consider:

There are some cultures where only a given name is provided at birth. These mononymous individuals legally have no surname.. or the reverse could apply and only has a surname.

Many names are hyphenated.. but shouldn't begin with one, end with one, or have more than one in sequence.

Many names contain apostrophes, such as O'Brien.

I'm sure there are plenty of other edge cases. You might want to consider the only validation for full name should be that it's not empty.

1 like
jlrdw's avatar

A. J. Smith

J. C. Doe

Don't forget about initials.

I've never seen anything like this come up.

I just validate and make sure it's the proper type characters in that field.

What's to prevent someone from entering.

Zawe Cgyurcdddsar

I see Jeffrey always entering test names quickly where he is demonstrating for example posting a form or something.

1 like

Please or to participate in this conversation.