I am learning to program in Android and I have a question. I have an application with a TextView, a Button and a EditText and I want my application to: I open it, I type something in the edittext and when I press the button, I want to check the text in the edittext if it's a valid email (using regular expressions) and display a message accordingly in the textview.
Asked
Active
Viewed 128 times
-1
-
No, I know how to validate the email, I want to know what is the correct way to get the text from the edit text and check it. – MrSilent Oct 23 '14 at 11:05
-
use `findViewById()` and pass the ID of the text box, next call `getText()` on it – TheLostMind Oct 23 '14 at 11:10
-
2`I know how to validate the email,`. Then please look at the subject of your post. `I want .... to get the text from the edit text`. Then please adapt the subject of your post. – greenapps Oct 23 '14 at 11:29
-
I have no idea whether you are asking about validating email addresses, validating an email's body (whatever that means) or ... simply getting the user's text from an `EditText`. If you don't fix your Question to make this clear, it is likely to be closed. – Stephen C Oct 23 '14 at 11:52
1 Answers
1
You can also check it without RegEx! You can put every character of the String into an Array of character. There you can check if there is a dot, a @ and so on...
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
This is the RegEx Expression -> Here is a Test Class
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public static void main(String[] args) {
EmailValidator em = new EmailValidator();
boolean y = em.validate("sakulreld@aol.com");
System.out.println(y);
}
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}

Lukas Hieronimus Adler
- 1,063
- 1
- 17
- 44