2013-07-30 36 views
1

我有一個問題....我想知道是否有可能在android中的輸入,如果它不是dateformat dd/mm/yyyy插入它將被拒絕編輯文本字段不知何故....我怎樣才能比較輸入的文字與我想要的格式?任何建議?我不認爲我需要發佈我的代碼,因爲我想要的只是一個普通的東西,我只需要一個例子或類似的東西,但我不知道該怎麼做。很多例子使用日期選擇器,但我不想使用那個...我想輸入它手動...請給我一些啓發請...拒絕,如果不是DateFormat

哦,是的,還有一件事,我找不到編輯文本與貨幣格式的字段。它不存在嗎?

+1

http://stackoverflow.com/questions/17416595/date-validation-in-android,http://www.mkyong.com/regular-expressions/how-to-validate-date -with-regular-expression/ –

+0

非常感謝您的參考@selva –

+0

不客氣@CharlesLynch –

回答

1

使用TextWatcher來偵聽對輸入字符串的更改,然後使用DateFormat格式化字符串並查看它是否符合所需的格式。

editText.addTextChangedListener(new TextWatcher() { 
@Override 
public void afterTextChanged(Editable s) { 
} 

@Override 
public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
} 

@Override 
public void onTextChanged(CharSequence s, int start, int before, int count) { 
    // you can check for validity here 
}); 
+0

不知何故,我對這個TextWatcher的東西有點困惑。但是謝謝你的回覆。 –

1

試試看。

public void checkFormate(final EditText mEditText) { 

      mEditText.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void onTextChanged(CharSequence arg0, int arg1, int arg2, 
       int arg3) { 
      SimpleDateFormat mdaDateFormat = new SimpleDateFormat(
        "yyyy-MM-dd"); 
      try { 
       mdaDateFormat.parse((String) arg0); 
      } catch (ParseException e) { 
       e.printStackTrace(); 
       mEditText.setError("Please enter proper date format"); 
      } 
      } 

      @Override 
      public void beforeTextChanged(CharSequence arg0, int arg1, 
       int arg2, int arg3) { 

      } 

      @Override 
      public void afterTextChanged(Editable arg0) { 

      } 
     }); 
    } 
+0

Thnsnk你我會嘗試.... –

+0

@CharlesLynch不要忘記標記答案,如果它的正確和投票的人,如果他們發佈一些有用的答案,以欣賞他們的幫助。 – Sameer

+0

是的,我會先試一下,然後再決定...... 感謝提醒 –

1
public boolean isValidDate(String date) 

{ 
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
    Date testDate = null;  
    try 
    { 
     testDate = sdf.parse(date); 
    } 
    catch (ParseException e) 
    { 
     errorMessage = "the date you provided is in an invalid date" + 
           " format."; 
     return false; 
    } 
    if (!sdf.format(testDate).equals(date)) 
    { 
     errorMessage = "The date that you provided is invalid."; 
     return false; 
    } 
    return true; 
}