如何在laravel中验证单词计数

use*_*060 3 php laravel laravel-4

我试图查看如何验证laravel中的单词数,例如,如果文本区域仅接受250个单词?

有人可以帮我我正在使用laravel 4.1

谢谢

小智 5

对于Laravel 5.1,并根据Lisa和Richard Le Poidevin的建议,我根据Laravel 5.1:Validation Docs进行了下一步,所有工作都非常整洁:

在“ app / Providers /”中为所有验证规则(包括执行验证的Validator :: extend方法和返回验证消息的Validator :: replacer)创建了一个新的ValidatorServiceProvider扩展服务提供者,以告知用户字数限制。

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(){
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

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

App\Providers\ValidatorServiceProvider::class,
Run Code Online (Sandbox Code Playgroud)

对于验证语言,响应是resources / lang / en / validation.php:

"maxwords" => "This field must have less than :maxwords words.",
Run Code Online (Sandbox Code Playgroud)


c-g*_*fin 4

我认为 Laravel 没有为此提供特定的方法,但您可以使用一些简单的 php 来完成。

在你的控制器中:

public function store(){

    $text = Input::get('textarea');

    if(count(explode(' ', $text)) > 250)
        return 'more than 250 words';

}
Run Code Online (Sandbox Code Playgroud)

  • 您可以只使用 str_word_count()。 (2认同)