验证edittext电子邮件没有工作android工作室

时间:2016-05-23 07:48:09

标签: android validation email android-edittext

我已尝试制作验证电子邮件,但显示的邮件始终是无效的电子邮件

我的代码:

public class MainActivity extends AppCompatActivity {

EditText txtEmail, txtPassword;
Button btnLogin;

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

    txtEmail = (EditText)findViewById(R.id.input_email);
    txtPassword = (EditText)findViewById(R.id.input_password);

    final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
    final String email = txtEmail.getText().toString().trim();



    btnLogin = (Button) findViewById(R.id.btn_login);
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //startActivity(new Intent(MainActivity.this, DashboardActivity.class));
            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();
            }

        }
    });
}

2 个答案:

答案 0 :(得分:0)

您需要在按钮 OnClick()

中获取 EditText 文字
 btnLogin.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final String email = txtEmail.getText().toString().trim();

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

    }
});

这可能对你有所帮助。

编辑1

你可以使用android的简单验证方法,

public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
    return false;
} else {
    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
  

注意:它将在Android 2.2及更高版本上运行!!

答案 1 :(得分:0)

试试这个方法

public boolean isEmailValid(EditText email) {
    boolean isValid = false;

    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email.getText().toString().trim();

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
}