Reputation: 1893
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?
Upvotes: 179
Views: 365496
Reputation: 1384
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();
}
Upvotes: 0
Reputation: 1010
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
Upvotes: -2
Reputation: 128428
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!
Upvotes: 14
Reputation: 9651
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
Upvotes: 100
Reputation: 4832
Why don't you use TextWatcher
?
Since you have a number of EditText
boxes to be validated, I think the following shall suit you :
android.text.TextWatcher
interfacetxt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
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.
Upvotes: 160
Reputation: 2167
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;
}});
Upvotes: 2
Reputation: 309
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
Upvotes: 2
Reputation: 3962
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.
}
}
Upvotes: 5
Reputation: 39225
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 */
}
});
Upvotes: 135
Reputation: 19723
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.
Upvotes: 27
Reputation: 9674
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});
Upvotes: 11
Reputation: 27613
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:
You can check it out here
Hope you enjoy it :)
Upvotes: 8
Reputation: 138
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.
Upvotes: 7
Reputation: 1845
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.
Upvotes: 6