I want to validate an email introduced inside an EditText and this the code that I already have:
final EditText textMessage = (EditText)findViewById(R.id.textMessage);
final TextView text = (TextView)findViewById(R.id.text);
textMessage.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (textMessage.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && s.length() > 0)
{
text.setText("valid email");
}
else
{
text.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
The problem is that when I introduce 3 characters after the "@", it appears the message "valid email", when it must appear when I introduce the complete email.
Any suggerence?
Thank you all!
I wrote a library that extends EditText which supports natively some validation methods and is actually very flexible.
Current, as I write, natively supported (through xml attributes) validation methods are:
You can check it out here: https://github.com/vekexasia/android-form-edittext
Hope you enjoy it :)
In the page I linked you'll be able to find also an example for email validation. I'll copy the relative snippet here:
There is also a test app showcasing the library possibilities.
This is a screenshot of the app validating the email field.
If you are using API 8 or above, you can use the readily available
Patterns
class to validate email. Sample code:By chance if you are even supporting API level less than 8, then you can simply copy the
Patterns.java
file into your project and reference it. You can get the source code forPatterns.java
from this linkSeveral good options here including android.util.Patterns.EMAIL_ADDRESS for API 8+.
https://stackoverflow.com/a/7882950/1011746
Try this pattern.....
editText.addTextChangedListener(new TextWatcher() {