Let’s use this command to generate a rule which helps to validate word count.
php artisan make: rule wordCount
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.”;
}
}
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’;
}
}
Now let's import the above rule in controller as :
use App\Rules\wordCount;
And finally used this validation with any request with any minimun length of the request as:
$request->validate([
‘introduction’ => [‘required’, new wordCount(50)],
]);
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
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.
Hopes it works for you.
HAPPY CODING!!
Top comments (0)