[Android 開發] 如何檢查輸入的文字是否為 Email 格式?

在 Android 的開發上,我們通常會使用 EditText 來輸入文字,而如果今天我們有一個欄位需要使用者來填寫 Email,並且驗證使用者所填的資料是否正確,那麼該怎麼做呢?其實很簡單,只要下面兩個步驟,就可以驗證使用者輸入的文字是否為 Email 格式了。

android 1

首先,我們在 XML 中要先進行限制,讓使用者只能輸入 Email 格式所可以接受的字元。

<EditText
   android:id="@+id/edittext_email"
   android:singleLine="true"
   android:inputType="textEmailAddress" />

接下來,再於程式進行判斷即可。

private boolean isVaildEmailFormat()
{
    EditText etMail = (EditText)   findViewById(R.id.edittext_email);
    if (etMail == null) {
        return false;
    }
    return android.util.Patterns.EMAIL_ADDRESS.matcher(etMail.getText().toString()).matches();
}

如果要搜尋相關資料,可以搜尋關鍵字「android check email format」或是「android validate an e-mail address」這兩個關鍵字,就可以找到一堆資料了唷!

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
apm
apm
9 years ago

唔識填電子郵件,請幫忙??唔該!