Laravel Validation field must have 4 words

Viewed 697

i want make field name be written in a quadrilateral

same

  • "andy hosam rami entaida" or
  • "حسام احممد محمد متولى"

i tray

            'name' => 'regex:/^[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+\s[\wء-ي]+/

in english all true put in arabic is false

regex is true i test it hear regexr.com/57s61

i can do with php in another way , so how can write in laravel ?

if(count(explode(' ',$name)) < 4)
  {
     $error[] ='enter full name with 4 words';
  }
1 Answers

You can make a custom Rule class to do custom validation, in an encapsulated manner.

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NumWords implements Rule
{
    private $attribute;
    private $expected;
    
    public function __construct(int $expected)
    {
        $this->expected = $expected;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->attribute = $attribute;
        $trimmed = trim($value);
        $numWords = count(explode(' ', $trimmed));
        return $numWords === $this->expected;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The '.$this->attribute.' field must have exactly '.$this->expected.'  words';
    }
}

Then you can use it anywhere in validation, as below:

    public function rules()
    {
        return [
            'name' => [ 'required', 'string', new NumWords(4)],
        ];
    }
Related