首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在EditText内验证电子邮件

在EditText内验证电子邮件
EN

Stack Overflow用户
提问于 2011-10-02 18:34:44
回答 9查看 32.3K关注 0票数 16

我想验证一封在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",而当我介绍完整的电子邮件时,它必须出现。

有什么建议吗?

谢谢大家!

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2011-10-02 19:16:53

只需按如下方式更改您的正则表达式:

"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"

因为。(点)表示匹配任何单字符。在点前添加双反斜杠以表示实点。

票数 23
EN

Stack Overflow用户

发布于 2012-05-25 05:46:52

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

目前,在我写这篇文章时,原生支持的(通过 attributes)验证方法有:

自定义regexp

  • numeric:的
  1. regexp:仅用于数字field
  2. alpha:仅字母field
  3. alphaNumeric:猜测what?
  4. email:检查字段是否为有效的email
  5. creditCard:使用Luhn检查字段是否包含有效的信用卡Algorithm
  6. phone:检查字段是否包含有效的电话number
  7. domainName:检查该字段包含有效的域名(始终通过API级别<8的测试) )
  8. ipAddress:检查字段是否包含有效的ip地址webUrl:检查字段是否包含有效的url (始终通过API级别<8的测试)它不检查任何东西。(默认)

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

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

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

票数 15
EN

Stack Overflow用户

发布于 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();

}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7625862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档