2

I have three edit text to get values getting Email is one of them and I cant validation of specific validation of Email text so any one can suggest me how to do this...

my code is ....

        String Tomaail="feedback@earthcorporation.co.in";
        String Name=name.getText().toString();
        String Mail=mail.getText().toString().trim();
        String Phone=phone.getText().toString();
        String Feedback=feedback.getText().toString();
        String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

        if(Name.compareTo("") == 0 || Mail.compareTo("") == 0 || Phone.compareTo("") == 0 || Feedback.compareTo("") == 0)
        {
            if(Name.compareTo("") == 0)
            {
            name.setError("Enter Name");
            }
            else if (Mail.matches(emailPattern)  || Mail.compareTo("") == 0) 
            {
                mail.setError("Enter valid Address");
            }
            else if(Phone.compareTo("") == 0)
            {
                phone.setError("Enter Your Phone No.");
            }
            else
            {
                feedback.setError("Enter your Feedback");   
            }

            Toast.makeText(feedback.this,"Enter All Data",Toast.LENGTH_SHORT).show();

            }
            else
            {
SMR
  • 6,628
  • 2
  • 35
  • 56

4 Answers4

2
public final static boolean isValidEmail(CharSequence target) {
    if (target == null) {
        return false;
    } else {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
    }
}

If email Address is Valid Then it will Return True other Wise false

Digvesh Patel
  • 6,503
  • 1
  • 20
  • 34
0

The easiest method will be to use the inbuilt methods:

if(!android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches())
{
    mail.setError("Enter valid Address");
}

or you can do email validation using a regular expressions like this:

private static final String EMAIL_REGEX = "^[_a-z0-9-\\+]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

and validate it like this

......
else if (!Mail.matches(EMAIL_REGEX)) 
{
    mail.setError("Enter valid Address");
}
....

or you can also try the inbuilt matcher:


[EDIT]: changed REGEX to avoid CAP chars.

[NOTE]: make sure you have ! sign inside if otherwise you will suffer reverse effect.

Hope it helps. :)

SMR
  • 6,628
  • 2
  • 35
  • 56
0

Always start variable names with a lowercase letter.

If you need to check if a string is empty use either string.isEmpty() or string.length() == 0. If the string can be null, use TextUtils.isEmpty(string). String.compareTo("") == 0 is very bad.

And finally, for checking email validity use Patterns.EMAIL_ADDRESS.matcher(emailString).matches()

Erik Ghonyan
  • 427
  • 4
  • 12
0

return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();