2016-11-14 39 views
3

我已經創建了一個名爲form-field-input的通用表單組件,它可以驗證焦點輸出時的用戶輸入。Ember - 如何在其子組件上創建父組件觸發器行爲

形式場-input.hbs

<label>{{label}}</label> 
 
{{input 
 
placeholder=label 
 
value=value 
 
focus-out='validate' \t 
 
required=required 
 
type=type 
 
}} 
 
<p>{{errorMessage}}</p>

形式場-input.js

actions: { 
 
    validate: function() { 
 
    var type = this.get('type'); 
 
    this.set('checked', true); 
 
    if (this.get('required')) { 
 
     if (this.get('value') === '') { 
 
     this.set('invalid', true); 
 
     this.set('valid', false); 
 
     this.set('errorMessage', 'This field cannot be blank'); 
 
     return 
 
     } 
 
    } 
 
    if (type === 'Email') { 
 
     this.send('validateEmail'); 
 
    } 
 
    ... 
 
    }, 
 
}

如果我將組件的幾個實例放置到一個表單中(如下所示),當用戶關注每個輸入時,驗證完美起作用。

<form {{action "login" on="submit"}}> 
 
    {{form-field-input label='Email' value=email type='Email' required=true }} 
 
    {{form-field-input label='Password' value=password type='Password' required=true}} 
 
    {{input type="submit" value="Log In"}} 
 
</form>

我想驗證每個表單字段輸入組分當用戶點擊提交以及(所以單擊提交無填充的任何字段將觸發在每個驗證錯誤消息所需的表格字段組件)。

這是可以實現的,還是需要將驗證代碼放入父組件?

回答

5

表單由一些不同的輸入字段組成。每個輸入字段都與一個或多個數據屬性(比如模型)相關。表格反映了這種模式。驗證模型需要具有完整性。所以你不僅要檢查模型的字段,還要檢查模型本身的整體情況。

例如,認爲一個人物有兩個字段:出生年份和出生國家。您可能想要檢查該國是否存在於該年份。 (在1970年,沒有一個國家的名字是哈薩克斯坦)。你不能通過驗證單個字段來驗證這一點。

因此,在我看來,您應該對代表有意義的模型的父組件進行驗證。所以你應該將驗證數據傳遞給子組件。

示例僞代碼:

{{#form-component validationRules=validationRules as |f|}} 
    {{f.date-input value=(readonly birthDate) propertyName='birthDate'}} 
    {{f.text-input value=(readonly birthCountry) propertyName='birthCountry'}} 
{{/form-component}} 
+1

這個答案遵循「數據了,操作起來」餘燼的口頭禪,這是一個很好的做法在灰燼跟隨。 – damienc

相關問題