在使用打字稿的HTML應用程序中,我有一個HTML表單。該表格有一些必填字段。在我的打字稿文件我建立一個錯誤信息是這樣的:所需字段的較短驗證功能
hasErrors() {
let errorCount = 0;
if (!item.Field1()) {
this.ErrorText('"Field1"');
errorCount++;
}
if (!item.Field2()) {
if (errorCount > 0)
this.ErrorText(this.ErrorText() + ', "Field2"');
else
this.ErrorText('"Field2"');
errorCount++;
}
if (!item.Field3()) {
if (errorCount > 0)
this.ErrorText(this.ErrorText() + ', "Field3"');
else
this.ErrorText('"Field3"');
errorCount++;
}
// ...
if (errorCount > 1)
this.ErrorText("The fields " + this.ErrorText() + " are required.";
else if (errorCount == 1)
this.ErrorText("The field " + this.ErrorText() + " is required.";
else
return false;
return true;
}
正如你可以看到,這個功能會非常長,如果有需要,許多領域。有沒有更好/更短的方式來獲得相同的結果?
謝謝,這就是我一直在尋找的。 –