Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Email EditText Validation [duplicate]

Tags:

java

android

I have this EditText definition:

<EditText 
     android:layout_height="wrap_content" 
     android:layout_width="fill_parent"
     android:inputType="textEmailAddress" 
     android:id="@+id/EmailText"/>

Notice the EditText has the inputType defined with an email address specification. Does Android have anything built in to validate an email address input type, or does this all have to be done manually? It's allowing me to enter invalid data, so I'm curious as to its purpose.

Thanks.

like image 818
Brian Mains Avatar asked Feb 20 '12 03:02

Brian Mains


3 Answers

If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) 
        return false;

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

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 for Patterns.java from this link

like image 86
Mahendra Liya Avatar answered Nov 06 '22 10:11

Mahendra Liya


Here By giving input type Email you are setting the keyboard of email type means "@" and "." keyword will display on key board.

the better solution is to compare the email by following function

public boolean isEmailValid(String email)
    {
         String regExpn =
             "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                 +"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                   +"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                   +"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                   +"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";

     CharSequence inputStr = email;

     Pattern pattern = Pattern.compile(regExpn,Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(inputStr);

     if(matcher.matches())
        return true;
     else
        return false;
}

if this function returns true then your email address is valid otherwise not

like image 46
dilipkaklotar Avatar answered Nov 06 '22 12:11

dilipkaklotar


a bit better answers you can find here and here (credits to original authors)

boolean isEmailValid(CharSequence email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

or custom validation library https://github.com/vekexasia/android-form-edittext check second link for details and preview (regexp, numeric, alpha, alphaNumeric, email, creditCard, phone, domainName, ipAddress, webUrl)

Cheers

like image 18
Ewoks Avatar answered Nov 06 '22 10:11

Ewoks