問題描述
我們如何在 android
中的 edittext
上執行 Email Validation
?我已經通過 google &所以,但我沒有找到一種簡單的方法來驗證它.
How can we perform Email Validation
on edittext
in android
? I have gone through google & SO but I didn't find out a simple way to validate it.
推薦答案
要執行電子郵件驗證,我們有很多方法,但很簡單 &最簡單的方法是兩種方法.
To perform Email Validation we have many ways,but simple & easiest way are two methods.
1- 使用 EditText(....).addTextChangedListener
會不斷觸發 EditText 框
中的每個輸入,即 email_id 無效或有效
1- Using EditText(....).addTextChangedListener
which keeps triggering on every input in an EditText box
i.e email_id is invalid or valid
/**
* Email Validation ex:- tech@end.com
*/
final EditText emailValidate = (EditText)findViewById(R.id.textMessage);
final TextView textView = (TextView)findViewById(R.id.text);
String email = emailValidate.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\.+[a-z]+";
emailValidate .addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (email.matches(emailPattern) && s.length() > 0)
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
// or
textView.setText("valid email");
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show();
//or
textView.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// other stuffs
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// other stuffs
}
});
2- 使用 if-else
條件的最簡單方法.使用 getText() 獲取 EditText 框字符串并與為電子郵件提供的模式進行比較.如果模式不匹配或不匹配,按鈕的 onClick 會顯示一條消息.它不會在 EditText 框中的每個字符輸入時觸發.如下所示的簡單示例.
2- Simplest method using if-else
condition. Take the EditText box string using getText() and compare with pattern provided for email. If pattern doesn't match or macthes, onClick of button toast a message. It ll not trigger on every input of an character in EditText box . simple example shown below.
final EditText emailValidate = (EditText)findViewById(R.id.textMessage);
final TextView textView = (TextView)findViewById(R.id.text);
String email = emailValidate.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\.+[a-z]+";
// onClick of button perform this simplest code.
if (email.matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
這篇關于EditText 上 Android 中的電子郵件地址驗證的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!