Validate an email inside an EditText [duplicate]

2020-02-17 09:59发布

I want to validate an email introduced inside an EditText and this the code that I already have:

final EditText textMessage = (EditText)findViewById(R.id.textMessage);

final TextView text = (TextView)findViewById(R.id.text);

    textMessage.addTextChangedListener(new TextWatcher() { 
        public void afterTextChanged(Editable s) { 
            if (textMessage.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+") && s.length() > 0)
            {
                text.setText("valid email");
            }
            else
            {
                text.setText("invalid email");
            }
        } 
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 
        public void onTextChanged(CharSequence s, int start, int before, int count) {} 
    }); 

The problem is that when I introduce 3 characters after the "@", it appears the message "valid email", when it must appear when I introduce the complete email.

Any suggerence?

Thank you all!

9条回答
▲ chillily
2楼-- · 2020-02-17 10:33

Just change your regular expression as follows:

"[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"

Because . (dot) means match any single-char.ADD a double backslash before your dot to stand for a real dot.

查看更多
【Aperson】
3楼-- · 2020-02-17 10:39

Don't do it in code. You can use inputType attribute of EditText.

    <EditText 
        android:id="@+id/edit_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"/>
查看更多
Explosion°爆炸
4楼-- · 2020-02-17 10:41

// validate your email address format. Ex-abci@gmail.com

public boolean emailValidator(String email) 
{
    Pattern pattern;
    Matcher matcher;
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();
}
查看更多
登录 后发表回答