我想验证一封在EditText中引入的电子邮件,下面是我已经拥有的代码:
最终EditText textMessage = (EditText)findViewById(R.id.textMessage);
最终文本= ( 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) {}
});
问题是,当我在"@“后面引入3个字符时,它会显示消息"valid email",而当我介绍完整的电子邮件时,它必须出现。
有什么建议吗?
谢谢大家!
发布于 2011-10-02 19:16:53
只需按如下方式更改您的正则表达式:
"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
因为。(点)表示匹配任何单字符。在点前添加双反斜杠以表示实点。
发布于 2012-05-25 05:46:52
我写了一个扩展EditText的库,它本机支持一些验证方法,实际上非常灵活。
目前,在我写这篇文章时,原生支持的(通过 attributes)验证方法有:
自定义regexp
你可以在这里查看: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"
/>
还有一个测试应用程序展示了库的可能性。
这是应用程序验证电子邮件字段的屏幕截图。
发布于 2012-05-28 14:51:14
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();
}
https://stackoverflow.com/questions/7625862
复制相似问题