Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何验证laravel中的字数_Php_Laravel_Laravel 4 - Fatal编程技术网

Php 如何验证laravel中的字数

Php 如何验证laravel中的字数,php,laravel,laravel-4,Php,Laravel,Laravel 4,我试图了解如何验证laravel中的单词数,例如,如果一个文本区域只接受250个单词 有人能帮我吗?我正在使用laravel 4.1 谢谢我不认为Laravel有专门的方法,但是你可以用一些简单的php来实现 在控制器中: public function store(){ $text = Input::get('textarea'); if(count(explode(' ', $text)) > 250) return 'more than 250 w

我试图了解如何验证laravel中的单词数,例如,如果一个文本区域只接受250个单词

有人能帮我吗?我正在使用laravel 4.1


谢谢

我不认为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;
} );
Validator::extend('word\u count',函数($field,$value,$parameters){
$words=preg_split('@\s+@i',$value);

如果(count($words)针对Laravel 5.1,并根据Lisa和Richard Le Poidevin的建议,我根据以下各项完成了下一步的工作:

在“app/Providers/”中为所有验证规则创建了一个新的ValidatorServiceProvider扩展服务提供程序,包括执行验证的Validator::extend方法和返回formmated消息的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(){
        //
    }
}
对于验证语言,响应为resources/lang/en/validation.php:

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

谢谢你的帮助,我想我必须有一个自定义的。你可以使用str_word_count()。
str_word_count()
对英语以外的其他语言不起作用。它值得修剪$value,否则就不会有额外的单词了,因为它们在文本结尾有空格。$words=preg_split('@\s+@I',trim($value));
"maxwords" => "This field must have less than :maxwords words.",