In Android email validation is an important thing, if the user is entered an invalid email id then we need to show some alert messages to the user. This will be required in most of the Android application with uses some thing with email id. here i am writing some code to do this,
- public static boolean isEmailAddress(EditText editText, boolean required)
- {
- String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
- return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
- }
- public static boolean isValid(EditText editText, String regex, String errMsg, boolean required)
- {
- String text = editText.getText().toString().trim();
-
- editText.setError(null);
-
- if (required && !hasText(editText)) return false;
-
- if (required && !Pattern.matches(regex, text))
- {
- editText.setError(errMsg);
- return false;
- };
- return true;
- }
- public static boolean hasText(EditText editText)
- {
- String text = editText.getText().toString().trim();
- editText.setError(null);
-
- if (text.length() == 0)
- {
- editText.setError(REQUIRED_MSG);
- return false;
- }
- return true;
- }
This will return false if the entered email id is invalid otherwise true.