Android: How can I validate EditText input?

AndroidAndroid Edittext

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

Why don't you use TextWatcher ?

Since you have a number of EditText boxes to be validated, I think the following shall suit you :

  1. Your activity implements android.text.TextWatcher interface
  2. You add TextChanged listeners to you EditText boxes

txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);

3. 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.

Solution 2 - Android

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 */
    }
});

Solution 3 - Android

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

Screenshot of the use of setError taken from Donn Felker, the author of the linked post

Solution 4 - Android

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.

Solution 5 - Android

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!

Solution 6 - Android

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}); 

Solution 7 - Android

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:

  1. alpha
  2. alpha numeric
  3. numeric
  4. generic regexp
  5. string emptyness

You can check it out here

Hope you enjoy it :)

Solution 8 - Android

I find InputFilter to be more appropriate to validate text inputs on android.

Here's a simple example: https://stackoverflow.com/questions/3349121/how-do-i-use-inputfilter-to-limit-characters-in-an-edittext-in-android/4401227#4401227

You could add a Toast to feedback the user about your restrictions. Also check the android:inputType tag out.

Solution 9 - Android

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.

Solution 10 - Android

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.

Solution 11 - Android

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;
    }});  

Solution 12 - Android

In main.xml file

You can put the following attrubute to validate only alphabatics character can accept in edittext.

Do this :

  android:entries="abcdefghijklmnopqrstuvwxyz"

Solution 13 - Android

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();
}

Solution 14 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStefanView Question on Stackoverflow
Solution 1 - AndroidNiksView Answer on Stackoverflow
Solution 2 - AndroidChristopher PerryView Answer on Stackoverflow
Solution 3 - AndroidDonn FelkerView Answer on Stackoverflow
Solution 4 - AndroidRagunath JawaharView Answer on Stackoverflow
Solution 5 - AndroidParesh MayaniView Answer on Stackoverflow
Solution 6 - AndroidDaniel MagnussonView Answer on Stackoverflow
Solution 7 - AndroidAndrea BaccegaView Answer on Stackoverflow
Solution 8 - AndroidMoisésView Answer on Stackoverflow
Solution 9 - Androiduser405821View Answer on Stackoverflow
Solution 10 - AndroidAbsView Answer on Stackoverflow
Solution 11 - AndroidzasadnyyView Answer on Stackoverflow
Solution 12 - AndroidKKumarView Answer on Stackoverflow
Solution 13 - AndroidSyed Danish HaiderView Answer on Stackoverflow
Solution 14 - AndroidKarimView Answer on Stackoverflow