The OnFocusChangeListener is not working properly.

Asked 2 years ago, Updated 2 years ago, 183 views

I'd like to check my email when the focus of EditText is released.

Once you enter an email and move on to another EditText, it will work normally (whether normal or showing an error message).

However, if you go back to EditText where you enter the email, and modify it to not match the email format and move to another EditText, you will not see the error message.

signup_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String mailFormat = "^[_a-zA-Z0-9-\\.]+@[\\.a-zA-Z0-9-]+\\.[a-zA-Z]+$";
                if (hasFocus == false) {
                    String inputText = signup_email.getText().toString();
                    Pattern pattern = Pattern.compile(mailFormat);
                    Matcher matcher = pattern.matcher(inputText);
                    signup_email_layout.setErrorEnabled(false);
                    if (!matcher.matches())
                        signup_email_layout.setError ("invalid email input");
                }
            }
        });

onfocuschangelistener android regex

2022-09-22 21:54

1 Answers

I tested it with the code above setOnFocusChangeListener is being invoked well every time the focus changes. What is the setErrorEnabled(false); function doing? When do you set it to true? I think the flag setting is wrong :)

 signup_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String mailFormat = "^[_a-zA-Z0-9-\\.]+@[\\.a-zA-Z0-9-]+\\.[a-zA-Z]+$";
                if (hasFocus == false) {
                    String inputText = signup_email.getText().toString();
                    Pattern pattern = Pattern.compile(mailFormat);
                    Matcher matcher = pattern.matcher(inputText);
                    if (!matcher.matches()) {
                        Log.d ("TEST", "Email doesn't fit."); // I've tried logging. Every time the focus is shifted, the log is being taken well. 
                    }
                }
            }
        });


2022-09-22 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.