如何验证laravel中的单词计数


How to validate words count in laravel

我想看看如何验证laravel中的单词计数,例如,如果文本区域只接受250个单词?

谁能帮我一下,我正在使用laravel 4.1

谢谢

对于Laravel 5.1,并使用Lisa和Richard Le Poidevin的建议,我基于Laravel 5.1完成了接下来的步骤:验证文档,所有工作都很好,很干净:

在"app/Providers/"中为所有的验证规则创建了一个新的ValidatorServiceProvider扩展ServiceProvider,包括执行验证的Validator::extend方法和返回格式化消息的Validator::replacer,以便我们可以告诉用户字数限制。

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(){
        //
    }
}

然后,在config/app.php中注册服务提供商:

App'Providers'ValidatorServiceProvider::class,

验证语言响应为resources/lang/en/validation.php:

"maxwords" => "This field must have less than :maxwords words.",

我不认为Laravel有一个特定的方法,但你可以做一些简单的php。

在你的控制器:

public function store(){
    $text = Input::get('textarea');
    if(count(explode(' ', $text)) > 250)
        return 'more than 250 words';
}

当我去年遇到这个问题时,我最终是这样做的:

Validator::extend( 'word_count', function ( $field, $value, $parameters ) {
    $words = preg_split( '@'s+@i', $value );
    if ( count( $words ) <= $parameters[ 0 ] ) {
        return true;
    }
    return false;
} );

这将接受任何非空白字符集并将其视为'word',然后计算结果的数量。如果小于作为max ($parameters[0])发送的值,则返回true,否则返回false。

它可以与Laravel 4的验证器功能一起使用,但还没有在Laravel 5上测试过。