实时验证(按钮点击前)

时间:2017-12-27 20:23:44

标签: java android android-textwatcher

在用户点击按钮之前,有没有办法实时验证EditText字段。

例如,如果我有

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

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

使用validateEmail方法

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();
}

如何设置TextWatcher或其他内容以实时验证?

2 个答案:

答案 0 :(得分:2)

当一个类型的对象附加到Editable时使用

TextWatcher,当更改文本时将调用其方法。以下是设置Textwatcher的最简单方法:

   EditText inputName = (EditText) findViewById(R.id.input_name);
   EditText inputEmail = (EditText) findViewById(R.id.input_email);
   EditTextinputPassword = (EditText) findViewById(R.id.input_password);
   TextInputLayout inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);

   inputName.addTextChangedListener(new MyTextWatcher(inputName));
   inputEmail.addTextChangedListener(new MyTextWatcher(inputEmail));
   inputPassword.addTextChangedListener(new MyTextWatcher(inputPassword))

验证电子邮件

    private boolean validateEmail() {
    String email = inputEmail.getText().toString().trim();

    if (email.isEmpty() || !isValidEmail(email)) {
        inputLayoutEmail.setError(getString(R.string.err_msg_email));
        requestFocus(inputEmail);
        return false;
    } else {
        inputLayoutEmail.setErrorEnabled(false);
    }

    return true;
}

检查电子邮件是否有效

 private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
     }

实施他们,

private class MyTextWatcher implements TextWatcher {

    private View view;

    private MyTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    public void afterTextChanged(Editable editable) {
        switch (view.getId()) {
            case R.id.input_name:
                validateName();
                break;
            case R.id.input_email:
                validateEmail();
                break;
            case R.id.input_password:
                validatePassword();
                break;
        }
    }
}

我希望这对你有所帮助。

答案 1 :(得分:1)

你可以尝试

吗?
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) {

   }
  });