Tiffany
Tiffany

Reputation: 237

Error with checking for empty email string in Android

I have an activity that has two EditText boxes, one email and one plain text. I want to check that the email box is not empty and also that is matches an email pattern before allowing the user to move on. The pattern matcher part works, but the empty string part doesn't.

I validate as the user enters data, and then set the two buttons to the be clickable or not according to whether the email is correct. However, if the box is empty, it allows the user to press the button when it shouldn't. When there is text in the box, it does the correct thing of only letting the user press the button when the email pattern has been matched.

My after text changed method:

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            String enteredEmail = email.getText().toString();

            if (validateEmail(enteredEmail) == true) {
                image1.setImageResource(R.drawable.greentick);
                play.setClickable(true);
                play.setFocusable(true);
                existingUser.setClickable(true);
                existingUser.setFocusable(true);
            }

            else {
                System.out.println("Invalid");
                image1.setImageResource(R.drawable.redcross);
                play.setClickable(false);
                play.setFocusable(false);
                existingUser.setClickable(false);
                existingUser.setFocusable(false);
            }
        }

And my validateEmail() method:

public boolean validateEmail(String email) {

    boolean validated = false;
    if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() && (! email.equals("")) ) {
        validated = true;           
    }

    else {
        validated = false;
    }   
    return validated;
}

Upvotes: 1

Views: 284

Answers (2)

cjk
cjk

Reputation: 46465

TextChanged won't fire if the user hasn't entered anything, as the text hasn't changed... You should disable the button by default.

Have you tried debugging, as this should have shown you the event isn't firing.

Upvotes: 1

owen gerig
owen gerig

Reputation: 6172

this is how i validate email fields (regular expressions):

private Boolean validateEmail(String email)
{
    return email.matches("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
}

FYI: i dont remember offhand, you may need org.apache.commons.lang3.stringutils

Upvotes: 0

Related Questions