ValueParamValidator 類別將處理對 HowTo 動作中 Value 參數的驗證。本課程將詳細說明,如何建立程式碼來示範 com.ibm.carma.ui.parameterValidators 延伸點的參數確認和驗證功能。
針對本範例,下面是使用者可能輸入的內容清單,以及所顯示的參考訊息。
- 當使用者輸入 0 時,將顯示參考訊息
- 當使用者輸入 1 時,將顯示警告訊息
- 當使用者輸入 2 以上的值時,將顯示錯誤訊息
- 當使用者輸入非數值字元時,將不容許輸入
- 在套件瀏覽器視圖中,透過導覽 com.ibm.carma.plugin.howto > src > com.ibm.carma.plugin.howto.action,然後按兩下 ValueParamValidator 類別以在編輯器中開啟,來開啟該類別。
- 首先,您將實作 verifyInput 方法。
此方法會檢查輸入文字中的任何無效字元。針對本範例,此方法將只接受數值字元。下列虛擬碼對此進行了示範:
if the length of input is greater than 0
then allow input if the input characters are 0-9
else
do not allow input
請利用下列範例程式碼來實作 verifyInput 方法:
/*Accept only numeric characters as valid. */
public void verifyInput(ParameterValidationEvent event)
{
if(event.text.length() > 0)
event.allowInput = (event.text.matches("[0-9]"));
}
- 接下來,您將置換 validateParameter 方法,以根據輸入的值來顯示適當的方法,如上所述。 下列虛擬碼對此進行了示範:
if input = 0
return an informational message
else if input = 1
return a warning message
else
return an error message
請利用下列範例程式碼來置換此方法:
/* Returns an informational message if 0 is entered,
* Returns a warning message if 1 is entered,
* Returns an error message if a numeric value greater than 1 is entered
*/
public ValidationResult validateParameter(ParameterValidationevent event)
{
ValidationResult result = new ValidationResult();
if(event.text.contains("0"))
{
//Display informational message.
result.severity = ValidationResult.INFO;
result.message = "You entered a 0!";
}
else if(event.text.contains("1"))
{
//Display a warning message
result.severity = ValidationResult.WARNING;
result.message = "Values greater than 1 will result in an error!";
}
else
{
//Display an error message.
result.severity = ValidationResult.ERROR;
result.message = "Value is too great, enter a lower value.";
}
return result;
}
- 儲存原始檔,並對任何錯誤進行除錯。