Java 最佳实践:输入验证 (Android)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33072569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best Practice: Input Validation (Android)
提问by Salehin Rafi
I am new to android mobile development (Android Studio native development - for new knowledge). And here I want to ask a question regarding best practice for input validation. As far we know, when a developer develop input form. We need to prevent a user from key in a wrong input into the text field. So here is my question,
我是 android 移动开发的新手(Android Studio 原生开发 - 新知识)。在这里我想问一个关于输入验证最佳实践的问题。据我们所知,当开发人员开发输入表单时。我们需要防止用户在文本字段中输入错误的内容。所以这是我的问题,
- Can we create one java file for validation purpose only? All input form ,must go to that one validation file only (In case of many input page screen in one apps). If YES, how can I get an example/link/tutorial of that technique for my learning study. If NO, why?
- 我们可以创建一个仅用于验证目的的 java 文件吗?所有输入表单,必须只转到那个验证文件(如果一个应用程序中有多个输入页面屏幕)。如果是,我如何获得该技术的示例/链接/教程以进行学习研究。如果否,为什么?
From my point of view personally, it should have a way to implement the technique. So that we didn't need to reuse same code all over again for each java file (in term of clean code). Unfortunately, I didn't find any example or tutorial for that. Maybe I search a wrong keyword or misread. And if there is no such technique exist, what are the best practice for input validation?
从我个人的角度来看,它应该有一种实现该技术的方法。这样我们就不需要为每个 java 文件重新使用相同的代码(就干净的代码而言)。不幸的是,我没有找到任何示例或教程。也许我搜索了错误的关键字或误读了。如果不存在这样的技术,那么输入验证的最佳实践是什么?
Thank you.
谢谢你。
p/s: This thread for find a better way in best practice. Thank you.
p/s:此线程用于在最佳实践中找到更好的方法。谢谢你。
采纳答案by Randyka Yudhistira
This java class implements a TextWatcher
to "watch" your edit text, watching any changes done to the text:
这个 java 类实现了一个TextWatcher
来“观察”你的编辑文本,观察对文本所做的任何更改:
public abstract class TextValidator implements TextWatcher {
private final TextView textView;
public TextValidator(TextView textView) {
this.textView = textView;
}
public abstract void validate(TextView textView, String text);
@Override
final public void afterTextChanged(Editable s) {
String text = textView.getText().toString();
validate(textView, text);
}
@Override
final public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
/* Needs to be implemented, but we are not using it. */
}
@Override
final public void
onTextChanged(CharSequence s, int start, int before, int count) {
/* Needs to be implemented, but we are not using it. */
}
}
And in your EditText
, you can set that text watcher to its listener
在您的 中EditText
,您可以将该文本观察器设置为其侦听器
editText.addTextChangedListener(new TextValidator(editText) {
@Override public void validate(TextView textView, String text) {
/* Insert your validation rules here */
}
});
回答by PinoyCoder
One approach (which I am using) is you should have a helper for validating inputs such as:
一种方法(我正在使用)是您应该有一个帮助程序来验证输入,例如:
- Nullity (or emptiness)
- Dates
- Passwords
- Emails
- Numerical values
- and others
- 空虚(或空虚)
- 日期
- 密码
- 电子邮件
- 数值
- 和别的
here's an exerpt from my ValidationHelper class:
这是我的 ValidationHelper 类的摘录:
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
}
Now the way I use this class is this:
现在我使用这个类的方式是这样的:
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
}
You can call your validation by using TextWatcher
which is attached via EditText#addTextChangedListener
您可以使用以下TextWatcher
附件来调用您的验证EditText#addTextChangedListener
example:
例子:
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();
}
});