I have an Email EditText and i want to check it using email validation.
This's my email validation code
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public void showAlertValidation() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RegisterActivity.this);
alertDialog.setTitle("Failed");
alertDialog.setMessage("Invalid Email");
alertDialog.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
And this is my EditText validation code
editTextEmail= (EditText) findViewById(R.id.editTextEmail);
email = editTextEmail.getText().toString();
if(email.length() == 0) {
editTextEmail.setError("Email required!");
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else{
showAlertValidation();
}
}
The problem is the result of the EditText. When the value of EditText is null, it run showAlertValidation();
But if the value of EditText is "email" or "email@example" or "email@example.com", it not run showAlertValidation();
Anything wrong with my code?