Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate words count in laravel

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

like image 758
user3150060 Avatar asked Aug 22 '14 18:08

user3150060


People also ask

How do I count words in laravel?

The wordCount() method is one of many methods Laravel uses to manipulate strings. The wordCount() method counts the number of words in a string.

How many types of validation are there in laravel?

Each form request generated by Laravel has two methods: authorize and rules .

What is bail in laravel validation?

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.


1 Answers

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.",
like image 68
edumejia30 Avatar answered Oct 30 '22 16:10

edumejia30