Email validation on EditText - Android
We have a simple Email pattern matcher now
Java:
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
Kotlin Function:
private fun isValidEmail(email: String): Boolean {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
}
Kotlin Extension:
fun String.isValidEmail() =
!TextUtils.isEmpty(this) && Patterns.EMAIL_ADDRESS.matcher(this).matches()
You are mistakenly comparing your EditText
text length to 0, and only if it's true, you do your validation logic.
Here is is the correct code:
@Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
if(email.length() != 0) {
if (isValidEmail(email)) {
Toast.makeText(getApplicationContext(), "Valid email address!", Toast.LENGTH_SHORT).show();
}
else{
editTextEmail.setError("Email required!");
showAlertValidation();
}
}
else{
editTextEmail.setError("Email required!");
}
}