Search code examples
javaandroidandroid-textwatcher

Real time validation (before button click)


Is there any way to validate EditText fields in real time, before the user clicks a button.

For example, if I have

if (password.length() < 6) {
    passwordwrapper.setError("Password must have at least 6 characters");
    return;
}

and

if (!validateEmail(email)) {
    emailwrapper.setError("Invalid email");
    return;
}

with the validateEmail method being

private static final String EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"(),:;<>@\\[\\]\\\\]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$";
private Pattern pattern = Pattern.compile(EMAIL_PATTERN);
private Matcher matcher;

public boolean validateEmail(String email) {
    matcher = pattern.matcher(email);
    return matcher.matches();
}

How would I setup a TextWatcher or something else to validate it real time?


Solution

  • can you try

    Field1 = (EditText)findViewById(R.id.field1);
    
    
    Field1.addTextChangedListener(new TextWatcher() {
    
       public void afterTextChanged(Editable s) {}
    
       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }
    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {
    
       }
      });