2013-03-17 55 views
1

我想建立一個在線信息管理系統,這個系統會有一些中文輸入。但是,ZF2的驗證器無法驗證中文。我該怎麼做才能驗證中文輸入?創建一個自定義驗證器?如何創建一個?非常感謝你!!!如何讓ZF2的驗證器驗證中文輸入

Detail see here:

There are actually 3 languages which are not accepted in their own script. These languages 
are korean, japanese and **chinese** because this languages are using an alphabet where a 
single character is build by using multiple characters. 

In the case you are using these languages, the input will only be validated by using the 
english alphabet. 

回答

1

沒有這樣的驗證器用於ZF2中國人或日本人。

你可以做的是建立你自己的小驗證類。我結合Php check if the string has Chinese charsHow to check if the word is Japanese or English using PHP建立由extending the abstract validator這兩個小驗證你:

namespace MyApp\Validator; 

use Zend\Validator\AbstractValidator; 

// forgive the name of this class 
class IsNotOrientalLanguage extends AbstractValidator 
{ 
    /** 
    * {@inheritDoc} 
    */ 
    public function isValid($value) 
    { 
     $this->abstractOptions['messages'] = array(); 

     if (preg_match('/\p{Han}+/u', $value)) { 
      $this->abstractOptions['messages'][] = 'Chinese not allowed.'; 
     } 

     if (preg_match('/[\x{4E00}-\x{9FBF}]/u', $value)) { 
      $this->abstractOptions['messages'][] = 'Kankji not allowed.'; 
     } 

     if (preg_match('/[\x{3040}-\x{309F}]/u', $value)) { 
      $this->abstractOptions['messages'][] = 'Hiragana not allowed.'; 
     } 

     if (preg_match('/[\x{30A0}-\x{30FF}]/u', $value)) { 
      $this->abstractOptions['messages'][] = 'Katakana not allowed.'; 
     } 

     return ! $this->abstractOptions['messages']; 
    } 
} 

現在你可以使用這個驗證,無論你想:

use Zend\InputFilter\Input; 
use MyApp\Validator\IsNotOrientalLanguage; 

$input = new Input('blog_post'); 

$input->getValidatorChain()->attach(new IsNotOrientalLanguage());