gpt4 book ai didi

java - 实时验证(点击按钮前)

转载 作者:行者123 更新时间:2023-11-29 04:22:54 26 4
gpt4 key购买 nike

有什么方法可以在用户单击按钮之前实时验证 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 或其他东西来实时验证它?

最佳答案

TextWatcher当类型的对象附加到 Editable 时使用,当文本更改时将调用其方法。这是设置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;
}
}
}

希望对您有所帮助。

关于java - 实时验证(点击按钮前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com