DEV Community

ssbhattarai
ssbhattarai

Posted on

Create Custom laravel 8 rule to count the word of the request

Let’s use this command to generate a rule which helps to validate word count.

php artisan make: rule wordCount
Enter fullscreen mode Exit fullscreen mode

This command will create the file at App/Rules with the name of wordCount.php and initially, it will contain the following code:

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class WordCount 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)
{
//
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return “Your message here.”;
}
}
Enter fullscreen mode Exit fullscreen mode

Copy and paste the following code for word count validation:

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class wordCount implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
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 more than ‘.$this->expected.’ words’;
}
}
Enter fullscreen mode Exit fullscreen mode

Now let's import the above rule in controller as :

use App\Rules\wordCount;
Enter fullscreen mode Exit fullscreen mode

And finally used this validation with any request with any minimun length of the request as:

$request->validate([
‘introduction’ => [‘required’, new wordCount(50)],
]);
Enter fullscreen mode Exit fullscreen mode

here the function wordCount accepts the dynamic argument like i used 50 as minimum wordCount for ‘introduction’ request.

Finally, use in blade as:

<textarea type=”text” name=”introduction” class=”form-control” rows=”4" placeholder=”{{translate(‘Introduction’)}}” required>{{ $member->member->introduction }}</textarea>
@error(‘introduction’)
@enderror
Enter fullscreen mode Exit fullscreen mode

All done, now it will display the error if it does not satisfy the wordcount like

The introduction field must have more than 50 words.

Enter fullscreen mode Exit fullscreen mode

Hopes it works for you.

HAPPY CODING!!

Top comments (0)