【Salesforce】【LWC】響應式驗證標準查詢輸入框
阿新 • • 發佈:2021-01-14
技術標籤:lightning web componentjavascripthtmlcomponents
應用場景
在使用lwc的標準查詢輸入標籤 lightning-input-field 中,有時候會需要驗證使用者的輸入內容,並且根據內容進行不同的處理。如果使用者的選擇不符合要求,則需要清除輸入的內容,並且提示使用者。
*補充說明:*標準查詢輸入標籤指 lightning-input-field 的 field-name 值為一個查詢(look-up)欄位。
響應式驗證
怎麼做到能夠清除標準輸入框的內容?其實很簡單,在標準標籤中新增上一個 value 屬性,並且在js中管理這個變數。
例:
html:
<lightning-input-field variant="standard" required class="slds-size--3-of-7 slds-m-left--xx-large" value={value} onchange={valid} field-name='LOOK_UP__c'></lightning-input-field>
js:
@track value
valid(event) {
const id = event.detail.value[0]
}
在查詢輸入框中,input值雖然在前端顯示的是Name,但是js中取到的是這條記錄的id,因此,在驗證方法中,需要對id值進行驗證。
Apex:
@AuraEnabled
public static Boolean valid(Id recordId) {
LOOK_UP__c = [SELECT Id, Name, ... FROM LOOK_UP__c WHERE Id = :recordId];
// ... some validation
validationResult = ...;
return validationResult
}
在js中,根據Apex返回的結果,做出相應的處理:
@track value
valid(event) {
const id = event. detail.value[0]
valid({recordId: id}).then(result => {
if (!!result) {
// valid
} else {
// invalid, clear the input
this.value = ''
}
})
}
注意,在invalid的情況下,清除了input框的入力值,在lwc框架下,這會自動把標準輸入框的內容清楚。這是對標籤的value屬性被清除做出的響應動作。
但是單單這樣是不夠的,當你第二次輸入,驗證失敗之後,輸入框的內容並不會像第一次一樣被清除。這是因為第二次輸入的前後,value值並沒有改變,一直是第一次被賦值的 ''
。因此標籤並沒有發現value的變化,從而不會做出響應式行為。
因此,需要在標籤的 onchange 事件中,手動改變value值:
valid(event) {
const id = event.detail.value[0]
// set the value to input value
this.value = id
valid({recordId: id}).then(result => {
if (!!result) {
// valid
} else {
// invalid, clear the input
this.value = ''
}
})
}
同時,因為使用者可能手動清除輸入框,這個情況下,不需要對空輸入進行驗證,所以為了避免這種情況,在呼叫Apex方法前,需要再加一層判斷:
valid(event) {
const id = event.detail.value[0]
// set the value to input value
this.value = id
if (!!id) {
valid({recordId: id}).then(result => {
if (!!result) {
// valid
} else {
// invalid, clear the input
this.value = ''
}
})
}
}
這樣,標準的查詢輸入就已經被加上自定義的驗證方法了,並且,根據驗證結果的不同,輸入框會響應式地作出清除內容等等行為。