如何检查edittext的文本是否是电子邮件地址?

发布于 2024-11-10 00:08:38 字数 154 浏览 0 评论 0原文

如何在不使用 javascript 和正则表达式的情况下检查 edittext 的文本是否为电子邮件地址? 在这里,我使用了 inputtype="textEmailAddress" 这是有效的,但没有显示错误消息。

how to check the text of edittext is email address or not without using javascript and regular expression?
Here I used inputtype="textEmailAddress" this is working but no error message is display.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

仲春光 2024-11-17 00:08:38

在 Android 2.2+ 上使用此:

boolean isEmailValid(CharSequence email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

例如:

EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();

// Check if email id is valid or not
if (!isEmailValid(getEmailId)){
    new CustomToast().Show_Toast(getActivity(), loginView,
        "Your Email Id is Invalid.");
}

On Android 2.2+ use this:

boolean isEmailValid(CharSequence email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

for example:

EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();

// Check if email id is valid or not
if (!isEmailValid(getEmailId)){
    new CustomToast().Show_Toast(getActivity(), loginView,
        "Your Email Id is Invalid.");
}
捶死心动 2024-11-17 00:08:38
/**
 * method is used for checking valid email id format.
 * 
 * @param email
 * @return boolean true for valid false for invalid
 */
public static boolean isEmailValid(String email) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

在此函数中传递您的编辑文本字符串。

为了进行正确的电子邮件验证,您需要服务器端身份验证


注意 Android 中现在有一个内置方法,请参阅下面的答案。

/**
 * method is used for checking valid email id format.
 * 
 * @param email
 * @return boolean true for valid false for invalid
 */
public static boolean isEmailValid(String email) {
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

Pass your edit text string in this function .

for right email verification you need server side authentication


Note there is now a built-in method in Android, see answers below.

秋意浓 2024-11-17 00:08:38

请按照以下步骤进行:

步骤 1:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@+id/textView_email"
        android:layout_marginTop="40dp"
        android:hint="Email Adderess"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Email Validation Example" />

</RelativeLayout>

步骤 2:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

步骤 3:

public class MainActivity extends Activity {

private EditText email;

private String valid_email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initilizeUI();
}

/**
 * This method is used to initialize UI Components
 */
private void initilizeUI() {
    // TODO Auto-generated method stub

    email = (EditText) findViewById(R.id.editText_email);

    email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            Is_Valid_Email(email); // pass your EditText Obj here.
        }

        public void Is_Valid_Email(EditText edt) {
            if (edt.getText().toString() == null) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(edt.getText().toString()) == false) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else {
                valid_email = edt.getText().toString();
            }
        }

        boolean isEmailValid(CharSequence email) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                    .matches();
        } // end of TextWatcher (email)
    });

}

}

Please follow the following Steps

Step 1 :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@+id/textView_email"
        android:layout_marginTop="40dp"
        android:hint="Email Adderess"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Email Validation Example" />

</RelativeLayout>

Step 2:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

Step 3:

public class MainActivity extends Activity {

private EditText email;

private String valid_email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initilizeUI();
}

/**
 * This method is used to initialize UI Components
 */
private void initilizeUI() {
    // TODO Auto-generated method stub

    email = (EditText) findViewById(R.id.editText_email);

    email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            Is_Valid_Email(email); // pass your EditText Obj here.
        }

        public void Is_Valid_Email(EditText edt) {
            if (edt.getText().toString() == null) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(edt.getText().toString()) == false) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else {
                valid_email = edt.getText().toString();
            }
        }

        boolean isEmailValid(CharSequence email) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                    .matches();
        } // end of TextWatcher (email)
    });

}

}
允世 2024-11-17 00:08:38

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

当前,正如我所写,本地支持(通过xml属性)验证方法有:

  1. 正则表达式:用于自定义正则表达式
  2. 数字 >:对于仅数字字段
  3. alpha:对于仅alpha 字段
  4. alphaNumeric:猜猜怎么着?
  5. 电子邮件:检查该字段是否是有效的电子邮件
  6. 信用卡:使用 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"
       />  

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

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

通过 xml+library 完成电子邮件验证

I wrote a library that extends EditText which supports natively some validation methods and is actually very flexible.

Current, as I write, natively supported (through xml attributes) validation methods are:

  1. regexp: for custom regexp
  2. numeric: for an only numeric field
  3. alpha: for an alpha only field
  4. alphaNumeric: guess what?
  5. email: checks that the field is a valid email
  6. creditCard: checks that the field contains a valid credit card using Luhn Algorithm
  7. phone: checks that the field contains a valid phone number
  8. domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
  9. ipAddress: checks that the field contains a valid ip address
    webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
  10. nocheck: It does not check anything. (Default)

You can check it out here: https://github.com/vekexasia/android-form-edittext

Hope you enjoy it :)

In the page I linked you'll be able to find also an example for email validation. I'll copy the relative snippet here:

<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"
       />  

There is also a test app showcasing the library possibilities.

This is a screenshot of the app validating the email field.

email validation done thorugh xml+library

孤寂小茶 2024-11-17 00:08:38

正如其中一个答案中提到的,您可以使用 Patterns 类,如下所示:

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) 
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

如果您支持的 API 级别低于 8,那么您只需复制 Patterns.java 文件添加到您的项目中并引用它。您可以从 此链接

As mentioned in one of the answers you can use the Patterns class as below:

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) 
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link

巾帼英雄 2024-11-17 00:08:38

在您的情况下,您可以使用 android.util.Patterns 包

EditText email = (EditText)findViewById(R.id.user_email);

if(Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
    Toast.makeText(this, "Email is VALID.", Toast.LENGTH_SHORT).show();
else
    Toast.makeText(this, "Email is INVALID.", Toast.LENGTH_SHORT).show();

In your case you can use the android.util.Patterns package.

EditText email = (EditText)findViewById(R.id.user_email);

if(Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
    Toast.makeText(this, "Email is VALID.", Toast.LENGTH_SHORT).show();
else
    Toast.makeText(this, "Email is INVALID.", Toast.LENGTH_SHORT).show();
放赐 2024-11-17 00:08:38

下面的代码应该对你有用。

String email;
check.setOnClickListener(new OnClickListener() {


                public void onClick(View arg0) {

                    checkEmail(email);
                    if (checkMail) {
                        System.out.println("Valid mail Id");
                    }
                }
            });

        }
    }

    public static boolean checkEmail(String email) {

        Pattern EMAIL_ADDRESS_PATTERN = Pattern
                .compile("[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}" + ")+");
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

The following code should be useful to you.

String email;
check.setOnClickListener(new OnClickListener() {


                public void onClick(View arg0) {

                    checkEmail(email);
                    if (checkMail) {
                        System.out.println("Valid mail Id");
                    }
                }
            });

        }
    }

    public static boolean checkEmail(String email) {

        Pattern EMAIL_ADDRESS_PATTERN = Pattern
                .compile("[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}" + ")+");
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
南巷近海 2024-11-17 00:08:38

对于电子邮件地址验证,请尝试这个简单易行的代码。

    String email = inputEmail.getText().toString().trim();

    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
    {
        inputEmail.setError("Enter Valid Email Address");
        inputEmail.requestFocus();
    }

For Email Address validation try this simple and easy code.

    String email = inputEmail.getText().toString().trim();

    if (!Patterns.EMAIL_ADDRESS.matcher(email).matches())
    {
        inputEmail.setError("Enter Valid Email Address");
        inputEmail.requestFocus();
    }
猫烠⑼条掵仅有一顆心 2024-11-17 00:08:38

这里的 email 是您的电子邮件 ID。

  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();

    }

here email is your email-id.

  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();

    }
只怪假的太真实 2024-11-17 00:08:38

Apache Commons Validator 可以按照其他答案中提到的方式使用。

步骤:1)从此处下载jar文件

步骤:2)添加将其导入到您的项目库中

导入:

import org.apache.commons.validator.routines.EmailValidator;

代码:

String email = "[email protected]";
boolean valid = EmailValidator.getInstance().isValid(email);

并允许本地地址::

boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);

Apache Commons Validator can be used as mentioned in the other answers.

Step:1)Download the jar file from here

Step:2)Add it into your project libs

The import:

import org.apache.commons.validator.routines.EmailValidator;

The code:

String email = "[email protected]";
boolean valid = EmailValidator.getInstance().isValid(email);

and to allow local addresses::

boolean allowLocal = true;
boolean valid = EmailValidator.getInstance(allowLocal).isValid(email);
北音执念 2024-11-17 00:08:38

试试这个:

public boolean isValidEmail(String email) {
    return (PatternsCompat.EMAIL_ADDRESS.matcher(email).matches());
}

谢谢!

Try this:

public boolean isValidEmail(String email) {
    return (PatternsCompat.EMAIL_ADDRESS.matcher(email).matches());
}

Thanks!

蓝天白云 2024-11-17 00:08:38

一个简单的方法

    private boolean isValidEmail(String email)
{
    String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    if(email.matches(emailRegex))
    {
        return true;
    }
    return false;
}

A simple method

    private boolean isValidEmail(String email)
{
    String emailRegex ="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    if(email.matches(emailRegex))
    {
        return true;
    }
    return false;
}
远昼 2024-11-17 00:08:38
   I Hope this code is beneficial for you

    public class Register extends Activity 
      {
       EditText FirstName, PhoneNo, EmailId,weight;
       Button Register;
       private static final Pattern EMAIL_PATTERN = Pattern
        .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");


   private static final Pattern USERFIRSTNAME_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
   private static final Pattern PHONE_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
       @Override
   public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        Register=(Button) findViewById(R.id.register);

        FirstName=(EditText)findViewById(R.id.person_firstname);

            PhoneNo =(EditText)findViewById(R.id.phone_no);
            EmailId=(EditText)findViewById(R.id.email_id);
            weight=(EditText) findViewById(R.id.weight);

         Register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                sFirstName= FirstName.getText().toString();
                 sPhoneNo= PhoneNo.getText().toString();
                sEmailId= EmailId.getText().toString();
                sweight= weight.getText().toString(); 

                if(sFirstName.equals("")||sPhoneNo.equals("")||sEmailId.equals("")||sweight.equals(""))
                {
                    if ((!CheckUsername(sFirstName))) 
                     {
                     Toast.makeText(Register.this, "FirstName can not be null",Toast.LENGTH_LONG).show();
                     }
                   else if ((!Checkphoneno(sPhoneNo)))
                       {
                    Toast.makeText(Register.this, "ENTER VALID mobile no ",Toast.LENGTH_LONG).show();
                       }
                    else if ((!CheckEmail(sEmailId)))
                       {
                      Toast.makeText(Register.this, "ENTER VALID EMAIL ID",Toast.LENGTH_LONG).show();
                       }
                    else if ((!Checkweight(sweight)))
                      {
                    Toast.makeText(Register.this, "ENTER Weight in kg",Toast.LENGTH_LONG).show();
                      }
               }

            }
                private boolean CheckEmail(String sEmailId) {

                    return EMAIL_PATTERN.matcher(sEmailId).matches();
                }



                private boolean CheckUsername(String sFirstName) {

                    return USERFIRSTNAME_PATTERN.matcher(sFirstName).matches();
                }
                private boolean Checkphoneno(String sPhoneNo) {

                    return PHONE_PATTERN.matcher(sPhoneNo).matches();
                }
                private boolean Checkweight(String sweight) {

                    return Weight_PATTERN.matcher(sweight).matches();
                }


        });
   I Hope this code is beneficial for you

    public class Register extends Activity 
      {
       EditText FirstName, PhoneNo, EmailId,weight;
       Button Register;
       private static final Pattern EMAIL_PATTERN = Pattern
        .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");


   private static final Pattern USERFIRSTNAME_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
   private static final Pattern PHONE_PATTERN = Pattern
        .compile("[a-zA-Z0-9]{1,250}");
       @Override
   public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        Register=(Button) findViewById(R.id.register);

        FirstName=(EditText)findViewById(R.id.person_firstname);

            PhoneNo =(EditText)findViewById(R.id.phone_no);
            EmailId=(EditText)findViewById(R.id.email_id);
            weight=(EditText) findViewById(R.id.weight);

         Register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                sFirstName= FirstName.getText().toString();
                 sPhoneNo= PhoneNo.getText().toString();
                sEmailId= EmailId.getText().toString();
                sweight= weight.getText().toString(); 

                if(sFirstName.equals("")||sPhoneNo.equals("")||sEmailId.equals("")||sweight.equals(""))
                {
                    if ((!CheckUsername(sFirstName))) 
                     {
                     Toast.makeText(Register.this, "FirstName can not be null",Toast.LENGTH_LONG).show();
                     }
                   else if ((!Checkphoneno(sPhoneNo)))
                       {
                    Toast.makeText(Register.this, "ENTER VALID mobile no ",Toast.LENGTH_LONG).show();
                       }
                    else if ((!CheckEmail(sEmailId)))
                       {
                      Toast.makeText(Register.this, "ENTER VALID EMAIL ID",Toast.LENGTH_LONG).show();
                       }
                    else if ((!Checkweight(sweight)))
                      {
                    Toast.makeText(Register.this, "ENTER Weight in kg",Toast.LENGTH_LONG).show();
                      }
               }

            }
                private boolean CheckEmail(String sEmailId) {

                    return EMAIL_PATTERN.matcher(sEmailId).matches();
                }



                private boolean CheckUsername(String sFirstName) {

                    return USERFIRSTNAME_PATTERN.matcher(sFirstName).matches();
                }
                private boolean Checkphoneno(String sPhoneNo) {

                    return PHONE_PATTERN.matcher(sPhoneNo).matches();
                }
                private boolean Checkweight(String sweight) {

                    return Weight_PATTERN.matcher(sweight).matches();
                }


        });
轮廓§ 2024-11-17 00:08:38
public static boolean isEmailValid(String email) {
    boolean isValid = false;

    String expression = "^(([\\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})$";
    // "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (!matcher.matches()) {
        isValid = true;
    }
    return isValid;
}
public static boolean isEmailValid(String email) {
    boolean isValid = false;

    String expression = "^(([\\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})$";
    // "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (!matcher.matches()) {
        isValid = true;
    }
    return isValid;
}
把昨日还给我 2024-11-17 00:08:38

对于 Kotlin

fun emailValidation(email: String?): Boolean {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}

For Kotlin:

fun emailValidation(email: String?): Boolean {
    return Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
べ繥欢鉨o。 2024-11-17 00:08:38

对于电子邮件验证尝试这个。

public boolean checkemail(String email)
{

    Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();

}

for email validation try this.

public boolean checkemail(String email)
{

    Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();

}
〃安静 2024-11-17 00:08:38

你可以通过正则表达式来检查

    public boolean isValid(String strEmail)
    {
        pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
            matcher = pattern.matcher(strEmail);

        if (strEmail.isEmpty()) {
           return false;
        } else if (!matcher.matches()) {
            return false;
        }
        else
        {
        return true;
        }
     }

You can check it by regular expression

    public boolean isValid(String strEmail)
    {
        pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
            matcher = pattern.matcher(strEmail);

        if (strEmail.isEmpty()) {
           return false;
        } else if (!matcher.matches()) {
            return false;
        }
        else
        {
        return true;
        }
     }
寒冷纷飞旳雪 2024-11-17 00:08:38
private boolean isValidEmailID(String email) {
    String 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(PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

更多验证请点击此处

private boolean isValidEmailID(String email) {
    String 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(PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

For more validation click here

堇年纸鸢 2024-11-17 00:08:38

使用 android.util.Patterns 和 Kotlin 就非常简单了。返回布尔值的一行函数。

fun validateEmail(email: String) = Patterns.EMAIL_ADDRESS.matcher(email)

With android.util.Patterns and Kotlin it's very simple. One line function which return Boolean value.

fun validateEmail(email: String) = Patterns.EMAIL_ADDRESS.matcher(email)
﹂绝世的画 2024-11-17 00:08:38

在 Kotlin 中,您可以通过简单的方法来验证电子邮件地址,而无需编写大量代码,也无需使用像“^[_A-Za-z0-9-\+]....”这样的正则表达式。

看看有多简单:

 fun validateEmail(emailForValidation: String): Boolean{
    
            return Patterns.EMAIL_ADDRESS.matcher(emailForValidation).matches()
        }

编写此电子邮件验证方法后,您只需输入要验证的电子邮件即可。
如果 validateEmail() 方法返回 true,则电子邮件有效;如果返回 false,则电子邮件无效。

以下是如何使用此方法的示例:

 val eMail: String = emailEditText.text.toString().trim()
 if (!validateEmail(eMail)){ //IF NOT TRUE
            Toast.makeText(context, "Please enter valid E-mail address", Toast.LENGTH_LONG).show()

            return //RETURNS BACK TO IF STATEMENT
        }

In Kotlin, an E-mail address you can validate by the simple method without writing a lot of code and bother yourself with a regular expression like "^[_A-Za-z0-9-\+]....".

Look how is simple:

 fun validateEmail(emailForValidation: String): Boolean{
    
            return Patterns.EMAIL_ADDRESS.matcher(emailForValidation).matches()
        }

After you write this method for e-mail validation you just need to input your e-mail which you want to validate.
If validateEmail() method returns true e-mail is valid and if false then e-mail is not valid.

Here is example how you can use this method:

 val eMail: String = emailEditText.text.toString().trim()
 if (!validateEmail(eMail)){ //IF NOT TRUE
            Toast.makeText(context, "Please enter valid E-mail address", Toast.LENGTH_LONG).show()

            return //RETURNS BACK TO IF STATEMENT
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文