Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Email Validation on EditText

I have one edittext and I would to to write email validation in my Editttext this is a xml code

<EditText
        android:id="@+id/mail"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignLeft="@+id/phone"
        android:layout_below="@+id/phone"
        android:layout_marginRight="33dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/edit_background"
        android:ems="10"
        android:hint="E-Mail"
        android:inputType="textEmailAddress"
        android:paddingLeft="20dp"
        android:textColor="#7e7e7e"
        android:textColorHint="#7e7e7e" >
</EditText>

and this is a java code

emailInput = mail.getText().toString().trim();

emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

if (emailInput.matches(emailPattern)) {
    Toast.makeText(getActivity(), "valid email address", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(getActivity(), "Invalid email address", Toast.LENGTH_SHORT).show();
    mail.setBackgroundResource(R.drawable.edit_red_line);
}

I can't validation. The toast message is always "Invalid email address". What am I doing wrong?

like image 745
BekaKK Avatar asked Sep 10 '25 02:09

BekaKK


2 Answers

Why not use:

public final static boolean isValidEmail(CharSequence target) {
  return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

As suggested here.

like image 180
Daniel Zolnai Avatar answered Sep 12 '25 17:09

Daniel Zolnai


I am posting very simple and easy answer of email validation without using any string pattern.

1.Set on click listener on button....

 button_resetPassword.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            CharSequence temp_emilID=username.getText().toString();//here username is the your edittext object...
            if(!isValidEmail(temp_emilID))
            {
                username.requestFocus();
                username.setError("Enter Correct Mail_ID ..!!");
                     or
                Toast.makeText(getApplicationContext(), "Enter Correct Mail_ID", Toast.LENGTH_SHORT).show();

            }
            else
           {
              correctMail.. 
             //Your action...

           }

         });

2.call the isValidEmail() i.e..

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

I hope it will helpful for you...

like image 34
sachin pangare Avatar answered Sep 12 '25 16:09

sachin pangare