KrL*_*ler 16 regex email android android-edittext
我想验证EditText中引入的电子邮件,以及我已经拥有的代码:
final EditText textMessage =(EditText)findViewById(R.id.textMessage);
final TextView text =(TextView)findViewById(R.id.text);
textMessage.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (textMessage.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && s.length() > 0)
{
text.setText("valid email");
}
else
{
text.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Run Code Online (Sandbox Code Playgroud)
问题是当我在"@"之后引入3个字符时,它会显示消息"有效电子邮件",当我在介绍完整的电子邮件时它必须出现.
有什么建议吗?
谢谢你们!
小智 23
只需更改正则表达式,如下所示:
"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
Run Code Online (Sandbox Code Playgroud)
因为.(点)表示在你的点之前匹配任何单个char.ADD双反斜杠代表一个真正的点.
And*_*ega 15
我编写了一个扩展EditText的库,它本身支持一些验证方法,实际上非常灵活.
目前,我写的, 原生支持(通过XML属性)的验证方法有:
你可以在这里查看:https://github.com/vekexasia/android-form-edittext
希望你喜欢它 :)
在我链接的页面中,您还可以找到电子邮件验证的示例.我将复制相关片段:
<com.andreabaccega.widget.FormEditText
style="@android:style/Widget.EditText"
whatever:test="email"
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="textEmailAddress"
/>
Run Code Online (Sandbox Code Playgroud)
还有一个测试应用程序展示了库的可能性.
这是验证电子邮件字段的应用程序的屏幕截图.

public boolean validateEmail(String email) {
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31885 次 |
| 最近记录: |