ragunathjawahar / android-saripaar

UI form validation library for Android
Apache License 2.0
3.22k stars 460 forks source link

Set error to TextInputLayout #199

Open anderscheow opened 7 years ago

anderscheow commented 7 years ago

How do set the error message from TextInputEditText to TextInputLayout???

Alfishan commented 7 years ago

Create TextInputLayoutAdapter

public class TextInputLayoutAdapter implements ViewDataAdapter<TextInputLayout, String> {

    @Override
    public String getData(final TextInputLayout til) {
        return getText(til);
    }

    private String getText(TextInputLayout til) {
        return til.getEditText().getText().toString();
    }
}

Define your validation

 @NotEmpty
 @BindView(R.id.til_username)
 TextInputLayout mTilUsername; 

implement Validator.ValidationListener and define Validator var

public class YourActivityOrFragment extends AppCompatActivity implements Validator.ValidationListener  { 
private Validator mValidator; ...

private void initValidator() {
        mValidator=new Validator(this);
        mValidator.setValidationListener(this);
        mValidator.registerAdapter(TextInputLayout.class, new TextInputLayoutAdapter());
        mValidator.setViewValidatedAction(view -> {
            if (view instanceof TextInputLayout) {
                ((TextInputLayout) view).setError("");
                ((TextInputLayout) view).setErrorEnabled(false);

            }
        });
    }

@Override
    public void onValidationSucceeded() {

    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        errors.get(0).getView().requestFocus();
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);
            if (view instanceof TextInputLayout) {
                ((TextInputLayout) view).setError(message);
                ((TextInputLayout) view).setErrorEnabled(true);

            } else {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        }
    }

...

PS Don't forget to call initValidator().

Alameen688 commented 6 years ago

Worked for me. Thanks

anburocky3 commented 4 years ago

error: lambda expressions are not supported in -source 1.7 (use -source 8 or higher to enable lambda expressions)