2013-08-21 81 views
0

我正在使用下面的代碼來驗證TextField是否爲空或0,然後向它添加一個錯誤類以給它一個背景顏色。如何驗證Ember選擇列表?

我有另一個隱藏的文本框,並且根據在Ember.Select中選擇的內容設置了一個值,如果沒有選擇一個值如何最好爲select添加/更改錯誤類?

App.NumField = Ember.TextField.extend({ 
    required: function() { 
    var valid = /^[1-9][0-9]*$/.test(this.get('value')); 
    return valid 
    }.property('value'), 
    classNameBindings: 'required:notreq:req' 
}); 

{{view App.NumField valueBinding="type"}} 
{{view Ember.Select contentBinding="App.Type" optionValuePath="content.id" optionLabelPath="content.type" valueBinding="type" prompt="Please select a type"}} 

感謝您的任何建議。

回答

0

我在一個非常相似的方式通過擴展Ember.Select並結合基於結果的有效或無效類,如果選擇的選擇是null或undefined實現這一點。我不確定這是否是最好的解決方案,所以讓我知道你是否知道更好的方法。這很快,對我來說效果很好。

App.SelectValidate = Ember.Select.extend({ 
    validate: function() { 
     var chosen = this.selection, 
      valid; 
     if (chosen === null || chosen === undefined) { 
      valid = false; 
     } else { 
      valid = true; 
     } 
     return valid 
    }.property('value'), 
    classNameBindings: 'validate:valid:invalid' 
}); 
0

我們使用Parsley.js(http://parsleyjs.org/)來驗證我們的形式,並與配合,我們只是擴大我們Ember.Select類包括「必需」和「香菜錯誤消息」的屬性,所以我們可以在我們的綁定中使用它們。

Ember.Select.reopen({ 
    attributeBindings: ['required', 'data-error-message'] 
}); 

{{view Ember.Select 
contentBinding="[Your Val]" 
optionValuePath="[Your Val]" 
optionLabelPath="[Your Val]" 
valueBinding="[Your Val]" 
prompt="Choose Option" 
required="required" 
data-error-message="Please select an option."}} 

所以你可以看到如何擴展控制通過查看parsleyjs.org文件,以處理更多的香菜驗證場景,這是一個很好做庫。

0

如果您正在努力將parsleyjs集成到您的CLI項目中,以下是我如何設置它。它有很多屬性。

創建initializers/reopen-textfield.js爲:

export default { 
    name: 'textfield-configuration', 
    initialize: function() { 
    Ember.TextField.reopen({ 
     attributeBindings: [ 
     'parsley-type', 
     'parsley-required-message', 
     'parsley-type-email-message', 
     'required', 
     'placeholder' 
     ] 
    }); 
    } 
}; 

創建initializers/reopen-checkbox.js爲:

export default { 
    name: 'checkbox-configuration', 
    initialize: function() { 
    Ember.Checkbox.reopen({ 
     attributeBindings: [ 
     'parsley-type', 
     'parsley-required-message', 
     'parsley-type-email-message', 
     'parsley-group', 
     'required', 
     'placeholder' 
     ] 
    }); 
    } 
}; 

我使用ember cli項目,以建立我的餘燼應用。

DEBUG: ------------------------------- 
DEBUG: Ember  : 1.5.1 vendor.js:15554 
DEBUG: Ember Data : 1.0.0-beta.8.2a68c63a vendor.js:15554 
DEBUG: Handlebars : 1.3.0 vendor.js:1555 
DEBUG: jQuery  : 2.1.1 
DEBUG: ------------------------------- 

這個帖子的時候當前設置