问题描述
我们如何在 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:- [email protected]
*/
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 中的电子邮件地址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!