2012-02-29 46 views
3

我在驗證表單組件時遇到問題,因爲我已將NotBlank和Type驗證都添加到整數字段中。Symfony 2 - 使用NotBlank和類型約束來驗證字段

我validation.yml如下所示:

Acme\StoreBundle\Entity\Foo: 
properties: 
    bar: 
     - NotBlank: 
       message: You must specify a bar 
     - Type: 
      type: integer 
      message: bar must be an integer 

我FormType文件如下所示:

$builder->add('bar', 'integer', array(
      'label' => bar', 
      'error_bubbling' => true 
)); 

當我鍵入 'ABC' 進入該領域並提交,驗證表單和getErrors(),報告的錯誤是 -

This value is not valid. 
You must specify a bar. 

任何想法什麼是錯的?我跑的Symfony 2.0.10

回答

0

我不知道,但也許這會有所幫助:

$builder->add('bar', 'integer', array(
     'label' => bar', 
     'invalid_message' => 'bar must be an integer' 
     'error_bubbling' => true 
)); 

檢查this

+0

這種讓我進了一步,但是現在我看到這兩個「酒吧必須是一個整數'和'你必須指定一個酒吧',而且,我不明白爲什麼我需要添加一個無效的消息到表單組件和驗證(基本上重複的代碼)? – Matt 2012-02-29 16:26:38

+0

我也不知道。也許你可以把空的無效消息,如''invalid_message'=>'''' – seferov 2012-02-29 16:30:27

0

你的問題可能與this問題。從問題的討論似乎問題的解決與此代碼

if ($form->isRoot() && $form->isSynchronized()) { 

我沒有測試它雖然更換line 40 of the DelegatingValidator.php。你可以嘗試並告訴結果:)。

+0

我已經添加了這條線作爲建議,這似乎沒有幫助,我仍然有同樣的問題:-( – Matt 2012-03-01 09:41:49

+0

以及我已經測試過,確實無效,驗證在[this]完成(https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Form/Extension/Validator/Validator/DelegatingValidator。 php#L80)line for the most most form root which is synchronized。第二個想法我認爲你不必將字段類型設置爲'integer',因爲你已經添加了'integer'類型驗證約束。 – 2012-03-01 16:44:06

1

我有同樣的問題。最後,我使用了一個普通的「文本」字段,並創建了自己的使用正則表達式的「整數」驗證器。

0

我很遲,但這樣可以幫助

  • validation.yml

contactNo:

 - NotBlank: ~ 
     - Regex: 
      pattern: '/\d/' 
      match: true 
      message: Your contact no. must be a number     
     - Length: 
      min: 10 
      max: 15 
      minMessage: 'You contact no. must be at least {{ limit }} digits.' 
      maxMessage: 'You contact no. can not be greater than {{ limit }} digits.'