I am trying to see how can I validate words count in laravel , for example if a text area accepts only 250 words?
Could some one help me I am using laravel 4.1
Thanks
The wordCount() method is one of many methods Laravel uses to manipulate strings. The wordCount() method counts the number of words in a string.
Each form request generated by Laravel has two methods: authorize and rules .
If you added more than one validation on your field like required, integer, min and max then if the first is fail then the other should stop to display an error message. right now by default, it prints others too. so you can prevent that by using the bail validation rule in laravel.
For Laravel 5.1 and using the advice of Lisa and Richard Le Poidevin, I did the nexts steps based on Laravel 5.1: Validation Docs and all works fine and clean:
Created a new ValidatorServiceProvider extending Service Provider in "app/Providers/" for all the validation rules including the Validator::extend method that does the validation and the Validator::replacer that returns a formmated message so we can tell the user the word limit.
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
class ValidatorServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(){
Validator::extend('maxwords', function($attribute, $value, $parameters, $validator) {
$words = preg_split( '@\s+@i', trim( $value ) );
if ( count( $words ) <= $parameters[ 0 ] ) {
return true;
}
return false;
});
Validator::replacer('maxwords', function($message, $attribute, $rule, $parameters) {
return str_replace(':maxwords', $parameters[0], $message);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register(){
//
}
}
Then, register the Service Provider in config/app.php:
App\Providers\ValidatorServiceProvider::class,
For the validation language response is resources/lang/en/validation.php:
"maxwords" => "This field must have less than :maxwords words.",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With