一种方法(我正在使用)是你应该有一个帮助器来验证输入,例如:
- 空性(或空性)
- 日期
- 密码
- 电子邮件
- 数值
- 和其他
这是我的验证助手类的摘录:
public class InputValidatorHelper {
public boolean isValidEmail(String string){
final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
public boolean isValidPassword(String string, boolean allowSpecialChars){
String PATTERN;
if(allowSpecialChars){
//PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
PATTERN = "^[a-zA-Z@#$%]\\w{5,19}$";
}else{
//PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
PATTERN = "^[a-zA-Z]\\w{5,19}$";
}
Pattern pattern = Pattern.compile(PATTERN);
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
public boolean isNullOrEmpty(String string){
return TextUtils.isEmpty(string);
}
public boolean isNumeric(String string){
return TextUtils.isDigitsOnly(string);
}
//Add more validators here if necessary
}
现在我使用这个类的方式是这样的:
InputValidatorHelper inputValidatorHelper = new InputValidatorHelper();
StringBuilder errMsg = new StringBuilder("Unable to save. Please fix the following errors and try again.\n");
//Validate and Save
boolean allowSave = true;
if (user.getEmail() == null && !inputValidatorHelper.isValidEmail(user_email)) {
errMsg.append("- Invalid email address.\n");
allowSave = false;
}
if (inputValidatorHelper.isNullOrEmpty(user_first_name)) {
errMsg.append("- First name should not be empty.\n");
allowSave = false;
}
if(allowSave){
//Proceed with your save logic here
}
您可以使用以下方式调用验证:TextWatcher
EditText#addTextChangedListener
例:
txtName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//Do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validate();
}
});