EditText 上的 Android 电子邮件验证

Posted

技术标签:

【中文标题】EditText 上的 Android 电子邮件验证【英文标题】:Android Email Validation on EditText 【发布时间】:2014-09-18 03:27:47 【问题描述】:

我有一个编辑文本,我想在我的 Editttext 中编写电子邮件验证 这是一个xml代码

<EditText
        android:id="@+id/mail"
        android:layout_
        android:layout_
        android:layout_alignLeft="@+id/phone"
        android:layout_below="@+id/phone"
        android:layout_marginRight="33dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/edit_background"
        android:ems="10"
        android:hint="E-Mail"
        android:inputType="textEmailAddress"
        android:paddingLeft="20dp"
        android:textColor="#7e7e7e"
        android:textColorHint="#7e7e7e" >
</EditText>

这是一个java代码

emailInput = mail.getText().toString().trim();

emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]2,)$";

if (emailInput.matches(emailPattern)) 
    Toast.makeText(getActivity(), "valid email address", Toast.LENGTH_SHORT).show();
 else 
    Toast.makeText(getActivity(), "Invalid email address", Toast.LENGTH_SHORT).show();
    mail.setBackgroundResource(R.drawable.edit_red_line);

我无法验证。 Toast 消息始终是“无效的电子邮件地址”。 我做错了什么?

【问题讨论】:

【参考方案1】:

为什么不使用:

public final static boolean isValidEmail(CharSequence target) 
  return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();

按照here的建议。

【讨论】:

这不会检测到诸如user@gmail.comn之类的拼写错误。【参考方案2】:

我在不使用任何字符串模式的情况下发布非常简单易行的电子邮件验证答案。

1.Set on click listener on button....

 button_resetPassword.setOnClickListener(new View.OnClickListener()
    
        @Override
        public void onClick(View v)
        
            CharSequence temp_emilID=username.getText().toString();//here username is the your edittext object...
            if(!isValidEmail(temp_emilID))
            
                username.requestFocus();
                username.setError("Enter Correct Mail_ID ..!!");
                     or
                Toast.makeText(getApplicationContext(), "Enter Correct Mail_ID", Toast.LENGTH_SHORT).show();

            
            else
           
              correctMail.. 
             //Your action...

           

         );

2.调用 isValidEmail() 即..

   public final static boolean isValidEmail(CharSequence target)
   
    if (TextUtils.isEmpty(target))
    
        return false;
     else 
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    
 

希望对你有帮助……

【讨论】:

【参考方案3】:

Android 电子邮件验证最简单的方法

   String validemail= "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]1,256" +

                        "\\@" +

                        "[a-zA-Z0-9][a-zA-Z0-9\\-]0,64" +

                        "(" +

                        "\\." +

                        "[a-zA-Z0-9][a-zA-Z0-9\\-]0,25" +

                        ")+";

               String emal=email.getText().toString();

                Matcher matcherObj = Pattern.compile(validemail).matcher(emal);



                        if (matcherObj.matches()) 

                               Toast.makeText(getApplicationContext(), "enter 

all details", Toast.LENGTH_SHORT).show();

                        

                        else 

                            Toast.makeText(getApplicationContext(),"please enter 

valid email",Toast.LENGTH_SHORT).show();

                        

【讨论】:

【参考方案4】:

试试下面的代码:

public final static boolean isValidEmail(CharSequence target) 
    return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();

这很好用。

【讨论】:

【参考方案5】:
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";


if(emailId.getText().toString().isEmpty()) 
 Toast.makeText(getApplicationContext(),"enter email address",Toast.LENGTH_SHORT).show();
else 
if (emailId.getText().toString().trim().matches(emailPattern)) 
  Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
  else 
  Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
  

【讨论】:

【参考方案6】:

这是登录验证的完整代码......

public class LoginActivity extends AppCompatActivity 
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;

@Bind(R.id.input_email) EditText _emailText;
@Bind(R.id.input_password) EditText _passwordText;
@Bind(R.id.btn_login) Button _loginButton;
@Bind(R.id.link_signup) TextView _signupLink;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    ButterKnife.bind(this);

    _loginButton.setOnClickListener(new View.OnClickListener() 

        @Override
        public void onClick(View v) 
            login();
        
    );

    _signupLink.setOnClickListener(new View.OnClickListener() 

        @Override
        public void onClick(View v) 
            // Start the Signup activity
            Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
            startActivityForResult(intent, REQUEST_SIGNUP);
            finish();
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        
    );


public void login() 
    Log.d(TAG, "Login");

    if (!validate()) 
        onLoginFailed();
        return;
    

    _loginButton.setEnabled(false);

    final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
            R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    // TODO: Implement your own authentication logic here.

    new android.os.Handler().postDelayed(
            new Runnable() 
                public void run() 
                    // On complete call either onLoginSuccess or onLoginFailed
                    onLoginSuccess();
                    // onLoginFailed();
                    progressDialog.dismiss();
                
            , 3000);



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    if (requestCode == REQUEST_SIGNUP) 
        if (resultCode == RESULT_OK) 

            // TODO: Implement successful signup logic here
            // By default we just finish the Activity and log them in automatically
            this.finish();
        
    


@Override
public void onBackPressed() 
    // Disable going back to the MainActivity
    moveTaskToBack(true);


public void onLoginSuccess() 
    _loginButton.setEnabled(true);
    finish();


public void onLoginFailed() 
    Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

    _loginButton.setEnabled(true);


public boolean validate() 
    boolean valid = true;

    String email = _emailText.getText().toString();
    String password = _passwordText.getText().toString();

    if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) 
        _emailText.setError("enter a valid email address");
        valid = false;
     else 
        _emailText.setError(null);
    

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) 
        _passwordText.setError("between 4 and 10 alphanumeric characters");
        valid = false;
     else 
        _passwordText.setError(null);
    

    return valid;

【讨论】:

请为您的答案添加一些解释【参考方案7】:

使用此功能验证电子邮件 ID:

 private boolean validateEmaillId(String emailId)

    return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]1|[\\w-]2,))@"
            + "((([0-1]?[0-9]1,2|25[0-5]|2[0-4][0-9])\\.([0-1]?"
            + "[0-9]1,2|25[0-5]|2[0-4][0-9])\\."
            + "([0-1]?[0-9]1,2|25[0-5]|2[0-4][0-9])\\.([0-1]?"
            + "[0-9]1,2|25[0-5]|2[0-4][0-9]))1|"
            + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]2,4)$").matcher(emailId).matches();

【讨论】:

【参考方案8】:

我在电子邮件模式中查询了多个电子邮件 ID 验证并且只有一个电子邮件 ID。我使用以下方法解决了它:

public static final String patter_emails="^(\\s*,?\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*@([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]2,9)+\\s*$";
public static final String patter_email="^(\\s*[0-9a-za-z]([-.\\w]*[0-9a-za-z])*@([0-9a-za-z][-\\w]*[0-9a-za-z]\\.)+[a-za-z]2,9)+\\s*$";

以上这些都用于Java和Android中的模式。

使用以下方法检查:

pattern test: rubular.com

【讨论】:

【参考方案9】:
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches()

【讨论】:

【参考方案10】:
private void isValidEmail(String email_id) 

        if (email_id == null)
            checkTextView.setVisibility(View.VISIBLE);
            checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
            return;
        
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(email_id).matches()) 
            checkTextView.setVisibility(View.GONE);
         else 
            checkTextView.setVisibility(View.VISIBLE);
            checkTextView.setText(LocaleController.getString("EnterValidEmail", R.string.EnterValidEmail));
        

获取一个 textView ex.checkTextView 并验证电子邮件何时有效,然后 textview 消失,否则它会显示消息

【讨论】:

【参考方案11】:

试试这个代码

String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`|~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`|~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.)3(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
        if (!tvEmail.matches(Constants.emailPattern))
            tvEmail.setError("Invalid Email ");
        
        else
            //your code
        

【讨论】:

【参考方案12】:

String emailPattern = "(?:[a-z0-9!#$%&'*+/=?^_`|~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`|~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.)3(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
if (!"anan.pp@gmail.co".matches(Constants.emailPattern))
    //tvEmail.setError("Invalid Email ");
 else 
    // your code

【讨论】:

【参考方案13】:

试试下面的代码:

只需调用下面的方法,

if(emailValidator(mail.getText().toString()))
Toast.makeText(getActivity(), "valid email address",
                    Toast.LENGTH_SHORT).show();

else
Toast.makeText(getActivity(), "invalid email address",
                    Toast.LENGTH_SHORT).show();



    public static boolean emailValidator(final String mailAddress) 

            Pattern pattern;
            Matcher matcher;

            final 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(mailAddress);
            return matcher.matches();

        

【讨论】:

【参考方案14】:

分配一个String变量来存储这个EditText的值:

emailInput = mail.getText().toString().trim();

在你的 EditText 中使用 setError:

if(!isValidEmail(emailInput))
   mail.setError("Invalid"); /*"Invalid Text" or something like getString(R.string.Invalid)*/
   mail.requestFocus();

创建一个检查电子邮件的方法:

private boolean isValidEmail(String emailInput) 
    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 = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(emailInput);
    return matcher.matches();

【讨论】:

以上是关于EditText 上的 Android 电子邮件验证的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中禁用 EditText

使用 C# 中的正则表达式操作检查 EditText 上的有效电子邮件 [关闭]

从edittext Android识别电子邮件

Android,从edittext中获取文本[重复]

在运行 Android 10 的小米设备上,EditText TextInput 中的电子邮件崩溃

在 android studio 中使用 EditText 上的数字键盘