I am using Android Data Binding framework I have suppose an EditText for login form with username as below
I just want to share my modification of the answer of Long Ranger for android arch viewModel:
public class StringValidationRules {
public static StringRule NOT_EMPTY = new StringRule() {
@Override
public boolean validate(Editable s) {
return TextUtils.isEmpty(s.toString());
}
};
public static StringRule EMAIL = new StringRule() {
@Override
public boolean validate(Editable s) {
return !android.util.Patterns.EMAIL_ADDRESS.matcher(s).matches();
}
};
public static StringRule PASSWORD = new StringRule() {
@Override
public boolean validate(Editable s) {
return s.length() < 8;
}
};
public interface StringRule {
boolean validate(Editable s);
}
}
the viewModel...
public class LoginViewModel extends ViewModel {
...
@BindingAdapter({"app:validation", "app:errorMsg"})
public static void setErrorEnable(EditText editText, StringValidationRules.StringRule stringRule, final String errorMsg) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (stringRule.validate(editText.getText())) {
editText.setError(errorMsg);
} else {
editText.setError(null);
}
}
});
}
...
and the XML:
...