Email Validation on EditText in android

2019-07-16 16:06发布

问题:

I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").

I don't want that it login with "\".`

@Override
public void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.main);
        WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);

        this.pref = PreferenceManager.getDefaultSharedPreferences(this);
        loginStatus = (TextView)findViewById(R.id.login_status);
        register = (Button) findViewById(R.id.btnregister);
        register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                RegisterIntent();
            }
        });

        login = (Button) findViewById(R.id.btlogin);
        password = (EditText) findViewById(R.id.txtPwd);
        username = (EditText) findViewById(R.id.txtemail);
        saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
        pref = getSharedPreferences(Constants.PREFS_NAME,
                MODE_PRIVATE);
        String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
        String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
        "");
        username.setText(usernamestr);
        password.setText(passwordsharestr);
        saveLogin = pref.getBoolean("saveLogin", false);
        if (saveLogin == true) {
            username.setText(usernamestr);
            password.setText(passwordsharestr);
            saveLoginCheckBox.setChecked(true);
        }

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    //Constants.clearInfo();
                    getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
                    .edit()
                    .putString(Constants.PREF_USERNAME,
                            username.getText().toString())
                            .putString(Constants.PREF_PASSWORD,
                                    password.getText().toString())
                                    .putString(Constants.PREF_CHECKED, "TRUE")
                                    .commit();


                    if (username.getText().toString().trim().equals("")) {
                        username.setError(Html
                                .fromHtml("Please Enter Username"));
                        username.requestFocus();
                    } else if (password.getText().toString().trim()
                            .equals("")) {
                        password.setError(Html
                                .fromHtml("Please Enter Password"));
                        password.requestFocus();
                    } else {
                        if (Constants
                                .checkInternetConnection(WiztangoActivity.this)) {
                            Constants.userpass = password.getText()
                            .toString();
                            new AuthenticData().execute();
                        } else {
                            WiztangoBaseApplication.ShowThisDialog("Error",
                            "Please check internet connection.");
                        }

                        if (saveLoginCheckBox.isChecked()) {

                            prefEditor.putBoolean("saveLogin", true);
                            prefEditor.putString(Constants.PREF_USERNAME,
                                    username.getText().toString());
                            prefEditor.putString(Constants.PREF_PASSWORD,
                                    password.getText().toString());
                            saveLoginCheckBox.setChecked(true);
                            prefEditor.commit();
                        } else {

                            SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE); 
                            SharedPreferences.Editor editor=mPreferences.edit();

                            editor.remove(Constants.PREF_USERNAME);
                            editor.remove(Constants.PREF_PASSWORD);
                            editor.commit();


                        }
                    }

                } catch (Exception e) {
                    Log.e("Exception In Wiztango/", e.toString());
                    e.printStackTrace();
                }
            }
        });
    } catch (Exception e) {
        Log.e("Exception In Wiztango/", e.toString());
        e.printStackTrace();
    }
}

回答1:

Inbuilt Patterns Provides Email Validation like:

if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
    emailEditText.setError("Invalid Email");
    emailEditText.requestFocus();
}


回答2:

Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882

It says:

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


回答3:

You can use this code for check is Valid Email or not:

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


回答4:

Best Approach

Validate email and isEmpty in one method.

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


回答5:

public static boolean isEmailValid(String email) {
        boolean isValid = false;

        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }


回答6:

Try out the below method to validate the Email address.

private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
    boolean m_isValid = false;
    try
    {
        if (p_editText != null)
        {
            if(validateForNull(editText,p_nullMsg))
            {
                Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Za-z]{2,4})");
                Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
                if (!m_matcher.matches() &&  editText.getText().toString().trim().length() > 0)
                {
                    m_isValid = false;
                    editText.setError(p_invalidMsg);
                }
                else
                {
                    m_isValid = true;
                }
            }
            else
            {
                m_isValid = false;
            }
        }
        else
        {
            m_isValid = false;
        }
    }
    catch(Throwable p_e)
    {
        p_e.printStackTrace(); // Error handling if application crashes
    }
    return m_isValid;
}


回答7:

Try this code:--

 public final static boolean isValidEmail(CharSequence target) {

 if (target == null) {
     return false;
 } else {
     return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
 }
}