Android 中 EditText 上的电子邮件地址验证 [英] Email Address Validation in Android on EditText

查看:30
本文介绍了Android 中 EditText 上的电子邮件地址验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在 android 中对 edittext 执行 Email Validation ?我已经通过谷歌 &所以,但我没有找到一种简单的方法来验证它.

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:- tech@end.com
*/


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 框字符串并与为电子邮件提供的模式进行比较.如果模式不匹配或匹配,则单击按钮吐司消息.它不会在 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();
}

这篇关于Android 中 EditText 上的电子邮件地址验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆