验证EditText中的电子邮件

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双反斜杠代表一个真正的点.

  • 这不是要验证`a @ foo .... com`而不是`@ foo.co.uk`或`@ foo9.com`? (3认同)
  • 就是这样,你必须逃脱这一点 (2认同)

And*_*ega 15

我编写了一个扩展EditText的库,它本身支持一些验证方法,实际上非常灵活.

目前,我写的, 原生支持(通过XML属性)的验证方法有:

  1. regexp:用于自定义正则表达式
  2. numeric:仅用于数字字段
  3. alpha:仅限alpha字段
  4. alphaNumeric:猜怎么着?
  5. 电子邮件:检查该字段是否为有效的电子邮件
  6. creditCard:使用Luhn算法检查该字段是否包含有效的信用卡
  7. 电话:检查该字段是否包含有效的电话号码
  8. domainName:检查该字段是否包含有效的域名(始终通过API级别<8的测试)
  9. ipAddress:检查该字段是否包含有效的IP地址webUrl:检查该字段是否包含有效的URL(始终通过API级别<8的测试)
  10. nocheck:它没有检查任何东西.(默认)

你可以在这里查看: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)

还有一个测试应用程序展示了库的可能性.

这是验证电子邮件字段的应用程序的屏幕截图.

电子邮件验证完成了thorugh xml +库


kyo*_*ogs 5

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)