I have made this code to try that EditTextEmail
you can only write an email if you write something that is not an email send aToast
EditText EditTextEmail;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
EditTextEmail = (EditText) findViewById(R.id.EditTextEmail);
final String compruebaemail = EditTextEmail.getEditableText().toString().trim();
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!compruebaemail.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+"))
{
Toast.makeText(MainActivity.this, "Por favor, introduce bien su email", Toast.LENGTH_LONG).show();
}
}
});
}
}
The problem is basically that I write what I write my commands Toast
as if I were writing badly.
Example of text with which it fails:
[email protected]
The variable
compruebaemail
is being assigned inonCreate
, before you enter the text.On the other hand, if it is assigned within the event
onClick
, only then will it have the last value entered.Note that I opted for another regular expression, taken from the answer to my question: Validating an email in JavaScript .
The problem that the regular expression you were using could have was that:
dot had to be escaped (if it doesn't match any character)
you had to allow more than 1 point (example
[email protected]
)possibly allow case in the domain (since you were only allowing
[a-z]
, and regular expressions are case sensitive by default)and allow other characters, valid in any e-mail (example:
+
).The regex I used does not apply to all valid emails, but in my opinion it will work for most cases. In fact, if all valid cases according to the RFC were really to be accepted, you would be accepting " aberrations " that one would normally not want to accept in a form. However, email validation is too broad a topic to be beyond the scope of this question.
You can perform validation using a
TextInputLayout
and use methodsetError()
to define the message,setErrorEnabled()
to enable it, for example:When the validation detects an incorrect email, the error message is enabled:
I add an example of
TextInputLayout
for the previous example:In this example, the validation is performed on the text entered in the
EdiText
with idmi_email
, based on the value obtained we determine whether or not to show the message through theTextInputLayout
.Since android version 2.2+ there is this method:
If you want an alternative, I propose the following:
The implementation in your code would be as follows:
If you wanted to use the first method, it would be exactly the same way.