[英]How to validate input value in a TextField in Java ME
我正在編寫一個簡單的SRMS,如果它符合某些標准,我需要驗證用戶的輸入,具體取決於字段,例如電子郵件字段或電話字段。 該應用程序將在特色手機中運行,因此我使用Java ME SDK和虛擬機進行測試。
這樣做的最佳方法是什么,驗證輸入的最佳方法是什么,如果輸入不符合某些條件,應該通知用戶還是將輸入的null
再次設置為null
。
public void name() {
boolean nameValid = false;
display = Display.getDisplay(this);
nameForm = new Form("Student Record Management (1/4");
TextField firstName = new TextField("First Name(s)", "", 20, TextField.ANY);
TextField lastName = new TextField("Last Name", "", 20, TextField.ANY);
TextField personNumber = new TextField("Person Number", "", 10, TextField.NUMERIC);
back = new Command("BACK", Command.BACK, 1);
next = new Command("Continue", Command.ITEM, 2);
nameForm.append(firstName);
nameForm.append(lastName);
nameForm.append(personNumber);
nameForm.addCommand(back);
nameForm.addCommand(next);
nameForm.setItemStateListener(this);
nameForm.setCommandListener(this);
display.setCurrent(nameForm);
if (firstName.toString().length() > 0) {
nameValid = true;
}
}
啟動代碼的人已實現CommandListener
和ItestStateListener
。
我不確定第二個做了什么,它有一個抽象的方法被填充,稱為itemStateChanged(Item item)
我應該檢查更改並在此處驗證?
public static boolean validateEmailID(String email) {
email = email.trim();
String reverse = new StringBuffer(email).reverse().toString();
if (email == null || email.length() == 0 || email.indexOf("@") == -1) {
return false;
}
int emailLength = email.length();
int atPosition = email.indexOf("@");
int atDot = reverse.indexOf(".");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLength);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
for (int i = 0; email.length() - 1 > i; i++) {
char i1 = email.charAt(i);
char i2 = email.charAt(i + 1);
if (i1 == '.' && i2 == '.') {
return false;
}
}
if (email.charAt(atPosition - 1) == '.' || email.charAt(0) == '.' || email.charAt(atPosition + 1) == '.' || afterAt.indexOf("@") != -1 || atDot < 2) {
return false;
}
return true;
}
ItemStateListener通知應用程序表單項中的更改。 當用戶更改表單中的項目或在Item中調用Item.notifyStateChanged()時,將調用itemStateChanged(Item item)項。 參數是更改值的Item(Textfield,DateField,ect)。
我建議您在CommandAction和ItemStateListener中調用驗證方法。 在itemStateChanged中,只應檢查當前Item(在參數中接收的那個)。 在CommandAction中,應檢查每個字段。 這樣每個項目都可以在任何情況下進行驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.