可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to do form input validation on a series of EditTexts. I\'m using OnFocusChangeListeners to trigger the validation after the user types into each one, but this doesn\'t behave as desired for the last EditText.
If I click on the \"Done\" button while typing into the final EditText then the InputMethod is disconnected, but technically focus is never lost on the EditText (and so validation never occurs).
What\'s the best solution?
Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?
回答1:
Why don\'t you use TextWatcher
?
Since you have a number of EditText
boxes to be validated, I think the following shall suit you :
- Your activity implements
android.text.TextWatcher
interface
- You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
- Of the overridden methods, you could use the
afterTextChanged(Editable s)
method as follows
@Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
The Editable s
doesn\'t really help to find which EditText box\'s text is being changed. But you could directly check the contents of the EditText boxes like
String txt1String = txt1.getText().toString();
// Validate txt1String
in the same method. I hope I\'m clear and if I am, it helps! :)
EDIT: For a cleaner approach refer to Christopher Perry\'s answer below.
回答2:
TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:
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) { /* Don\'t care */ }
@Override
final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don\'t care */ }
}
Just use it like this:
editText.addTextChangedListener(new TextValidator(editText) {
@Override public void validate(TextView textView, String text) {
/* Validation code here */
}
});
回答3:
If you want nice validation popups and images when an error occurs you can use the setError
method of the EditText
class as I describe here
回答4:
In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as @TextRule
, @NumberRule
, @Required
, @Regex
, @Email
, @IpAddress
, @Password
, etc.,
You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.
There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.
Here is a simple example that depicts the usage of the library.
@Required(order = 1)
@Email(order = 2)
private EditText emailEditText;
@Password(order = 3)
@TextRule(order = 4, minLength = 6, message = \"Enter at least 6 characters.\")
private EditText passwordEditText;
@ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
@Checked(order = 6, message = \"You must agree to the terms.\")
private CheckBox iAgreeCheckBox;
The library is extendable, you can write your own rules by extending the Rule
class.
回答5:
This was nice solution from here
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile(\"[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*\");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d(\"\", \"invalid\");
return \"\";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
回答6:
Updated approach - TextInputLayout:
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean)
and setError(CharSequence)
.
How to use it?
Step 1: Wrap your EditText with TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
android:id=\"@+id/layoutUserName\">
<EditText
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
android:hint=\"hint\"
android:id=\"@+id/editText1\" />
</android.support.design.widget.TextInputLayout>
Step 2: Validate input
// validating input on a button click
public void btnValidateInputClick(View view) {
final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
String strUsername = layoutLastName.getEditText().getText().toString();
if(!TextUtils.isEmpty(strLastName)) {
Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
layoutUserName.setErrorEnabled(false);
} else {
layoutUserName.setError(\"Input required\");
layoutUserName.setErrorEnabled(true);
}
}
I have created an example over my Github repository, checkout the example if you wish to!
回答7:
I find InputFilter to be more appropriate to validate text inputs on android.
Here\'s a simple example:
How do I use InputFilter to limit characters in an EditText in Android?
You could add a Toast to feedback the user about your restrictions.
Also check the android:inputType tag out.
回答8:
I wrote a class that extends EditText which supports natively some validation methods and is actually very flexible.
Current, as I write, natively supported through xml attributes validation methods are:
- alpha
- alpha numeric
- numeric
- generic regexp
- string emptyness
You can check it out here
Hope you enjoy it :)
回答9:
I needed to do intra-field validation and not inter-field validation to test that my values were unsigned floating point values in one case and signed floating point values in another. Here\'s what seems to work for me:
<EditText
android:id=\"@+id/x\"
android:background=\"@android:drawable/editbox_background\"
android:gravity=\"right\"
android:inputType=\"numberSigned|numberDecimal\"
/>
Note, you must not have any spaces inside \"numberSigned|numberDecimal\". For example: \"numberSigned | numberDecimal\" won\'t work. I\'m not sure why.
回答10:
This looks really promising and just what the doc ordered for me:
EditText Validator
public void onClickNext(View v) {
FormEditText[] allFields = { etFirstname, etLastname, etAddress, etZipcode, etCity };
boolean allValid = true;
for (FormEditText field: allFields) {
allValid = field.testValidity() && allValid;
}
if (allValid) {
// YAY
} else {
// EditText are going to appear with an exclamation mark and an explicative message.
}
}
custom validators plus these built in:
- regexp: for custom regexp
- numeric: for an only numeric field
- alpha: for an alpha only field
- alphaNumeric: guess what?
- personName: checks if the entered text is a person first or last name.
- personFullName: checks if the entered value is a complete full name.
- email: checks that the field is a valid email
- creditCard: checks that the field contains a valid credit card using Luhn Algorithm
- phone: checks that the field contains a valid phone number
- domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
- ipAddress: checks that the field contains a valid ip address
- webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
- date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
- nocheck: It does not check anything except the emptyness of the field.
回答11:
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries=\"abcdefghijklmnopqrstuvwxyz\"
回答12:
You can get desired behavior by listening when user hit \"Done\" button on keyboard, also checkout other tips about working with EditText in my post \"Android form validation - the right way\"
Sample code:
mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
validateAndSubmit();
return true;
}
return false;
}});
回答13:
for email and password validation try
if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7){
if (validatePassword(etpass1.getText().toString())) {
Toast.makeText(getApplicationContext(),\"Go Ahead\".....
}
else{
Toast.makeText(getApplicationContext(),\"InvalidPassword\".....
}
}else{
Toast.makeText(getApplicationContext(),\"Invalid Email\".....
}
public boolean validatePassword(final String password){
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = \"^(?=.*[0-9])(?=.*[A-Z])(?=.*
[@#$%^&+=!])(?=\\\\S+$).{4,}$\";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
回答14:
I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:
compile \'com.github.TeleClinic:SmartEditText:0.1.0\'
then you can use it like this:
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id=\"@+id/passwordSmartEditText\"
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
app:setLabel=\"Password\"
app:setMandatoryErrorMsg=\"Mandatory field\"
app:setPasswordField=\"true\"
app:setRegexErrorMsg=\"Weak password\"
app:setRegexType=\"MEDIUM_PASSWORD_VALIDATION\" />
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id=\"@+id/ageSmartEditText\"
android:layout_width=\"match_parent\"
android:layout_height=\"wrap_content\"
app:setLabel=\"Age\"
app:setMandatoryErrorMsg=\"Mandatory field\"
app:setRegexErrorMsg=\"Is that really your age :D?\"
app:setRegexString=\".*\\\\d.*\" />
Then you can check if it is valid like this:
ageSmartEditText.check()
For more examples and customization check the repository
https://github.com/TeleClinic/SmartEditText