2013-02-28 63 views
1

在我所在的服務器沒有啓用FILE_INFO後,我需要一種快速驗證單詞文檔的方法。laravel - 將消息添加到新註冊的驗證

Validator::register('word', function($attribute, $value, $parameters) 
{ 

    $valid_type = array(
     'application/msword', 
     'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
    ); 

    $valid_extentions = array(
     'doc', 
     'docx' 
    ); 

    if(! is_array($value)) 
    { 
     return false; 
    } 

    if(! isset($value['type'])) 
    { 
     return false; 
    } 

    if(! in_array(strtolower($value['type']), $valid_type)) 
    { 
     return false; 
    } 

    if(! in_array(strtolower(substr(strrchr($value['name'], '.') , 1)), $valid_extentions)) 
    { 
     return false; 
    } 

    return true; 

}); 

我知道這不是防彈但將盡現(添加建議,如果您有任何),但我怎麼添加一個消息這是目前它返回

validation.word 

什麼想法?

回答

1

您必須定義新的驗證規則和消息。

自定義規則是這樣的:

$rules = array(
    'input_file' => 'required|word', 
); 

這些消息看起來是這樣的:

$messages = array(
    'word' => 'The document must be .doc!', 
); 

最後你必須調用你的驗證規則和訊息:

$validator = Validator::make(Input::get(), $rules, $messages); 

結帳官方文檔Custom Validation

+0

這是偉大的!你知道我需要放置*自定義驗證規則*爲了成爲全球嗎?我使用Validator :: extend() – 2013-09-05 08:28:04

3

爲了使消息全球將它添加到/app/lang/en/validation.php主陣列中的「網址」後,像這樣

<?php 
return array(
    //... 
    "url"    => "The :attribute format is invalid.", 
    "word"    => "The document must be a Microsoft Word-file.", 
//.. 

爲了使自定義的驗證規則使用的全球/app/validators.php並添加類似以下內容:

<?php 

class CustomValidator extends Illuminate\Validation\Validator 
{ 
    //validate foo_bar 
    public function validateFooBar($attribute, $value, $parameters) 
    { 
     return ($value == 'foobar'); 
    } 
} 

Validator::resolver(function($translator, $data, $rules, $messages) 
{ 
    return new CustomValidator($translator, $data, $rules, $messages); 
}); 
+0

感謝您的帖子。對我真的很有幫助 – thangchung 2014-07-07 17:59:12