Validation allow only number and characters in edit text in android - android

In my application I have to validate the EditText. It should only allow character, digits, underscores, and hyphens.
Here is my code:
edittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// validation codes here
location_name=s.toString();
Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();
if (location_name.matches(".*[^a-z^0-9].*")) {
location_name = location_name.replaceAll("[^a-z^0-9]", "");
s.append(location_name);
s.clear();
Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
}
}
});
location.add(location_name);
When I enter input into EditText, the application is force closed.

Instead of using your "manual" checking method, there is something very easy in Android:
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++) {
if (!Character.isLetterOrDigit(source.charAt(i)) &&
!Character.toString(source.charAt(i)).equals("_") &&
!Character.toString(source.charAt(i)).equals("-"))
{
return "";
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
Or another approach: set the allowed characters in the XML where you are creating your EditText:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed" />

<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed"
/>
the above code will also include , additionally to avoid , use the following code
<EditText
android:inputType="text"
android:digits="0123456789qwertzuiopasdfghjklyxcvbnm_-"
android:hint="Only letters, digits, _ and - allowed"
/>

This can be useful, especially if your EditText should allow diacritics (in my case, Portuguese Diacritic):
<EditText
android:digits="0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÁáÂâÃãÀàÇçÉéÊêÍíÓóÔôÕõÚú"
/>

A solution similar to the android:digits="0123456789*", is to use this:
EditText etext = new EditText(this);
etext.setKeyListener(DigitsKeyListener.getInstance("0123456789*"));
An added bonus is that it also displays the numeric keypad.

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++) {
if (!Character.toString(source.charAt(i)).matches("[a-zA-Z0-9-_]+")) {
return "";
edittext.setError("Only letters, digits, _ and - allowed");
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });

Try this:
public static SpannableStringBuilder getErrorMsg(String estring) {
int ecolor = Color.BLACK; // whatever color you want
ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
return ssbuilder;
}
Then setError() to EditText when you want show 'only Letters and digits are allowed' as below.
etPhone.setError(getErrorMsg("Only lowercase letters and numbers are allowed!"));
Hope this will help you. I use the same for Validation Check in EditText in my apps.

please try adding the android:digits="abcde.....012345789" attribute? although the android:digits specify that it is a numeric field it does work for me to set it to accept letters as well, and special characters as well (tested on SDK-7)

You can validate this by two ways , both worked for me, hope will be helpful for you too.
1> Mentioning the chars in your edittext .
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
2> Can validate pragmatically as answered by milos pragmatically

use this 2 function
public static boolean isdigit(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return false;
}
return true;
}
public static boolean ischar(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return true;
}
return false;
}
pass Edittext variable in these function .. so you can have boolean value.

Related

Set max length to EditText layout_width

I'm currently doing an EditText where the user can type in one row of text. But I have the issue with setting it's max length. If I set it to a specific number it becomes very unpredictable since spaces takes up more for some reason. So I can type in "asdnknfoisanfo" etc and get the correct length I want, but when you start typing with spaces between the words the length get's smaller and doesn't fill the whole EditText.
<EditText
android:id="#+id/imageDescriptionTextEdit"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:hint="Enter a description of this picture.."
android:textSize="15sp"
android:textColorHint="#E9E9E9"
android:textColor="#ffffff"
android:maxEms="26"
android:imeOptions="actionDone"
android:typeface="monospace"
android:minEms="3"
android:singleLine="true"
fontPath="fonts/VarelaRound-Regular.ttf"
tools:ignore="MissingPrefix"/>
What I would say to be the ultimate solution is to set the length of characters to the length of the EditText itself. Then for sure, the user have the correct capacity always. Is this possible? Or are there another solution to my problem?
You can try with this.
String mStringStr = mEditText1.getText().toString().replaceAll("\\s", "");
Now you can get the actual length in string mStringStr(Without blank space)
mStringStr.length();
I hope this may help you.. :)
Try with this conditional
if(findViewById(R.id.imageDescriptionTextEdit).getText().toString().trim().length() <= "your max length here"){
//Do something
} else {
//Show alert message
}
What you can do is to remove the spaces from the input using below code
String input = Your_EditText.getText().toString();
input = input.replace(" ", "");
Then you can get the length of the string using
int inputlength = input.length();
Then you can check if the input is okay or not
so , overall the code should be
private final TextWatcher mywatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = Your_EditText.getText().toString();
input = input.replace(" ", "");
int inputlength = input.length();
if(inputlength>your_defined_length)
{
//do what you want to do
}
}
public void afterTextChanged(Editable s) {
}
};
Dont forget to add this watcher to your editText
Your_EditText.addTextChangedListener(mywatcher);
You can try it programatically :
final EditText et = (EditText)findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {
int yourMaxLength = 10;
boolean canNotAddMore = false;
String maxText = "";
public void afterTextChanged(Editable s) {
if(canNotAddMore){
et.removeTextChangedListener(this);
et.setText(maxText);
et.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String realCoontent = s.toString().trim().replace(" ", "");
if(realCoontent.length() >= yourMaxLength){
canNotAddMore = true;
maxText = s.toString();
}
}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
This example will remove the spaces from the list of characters counted to determine if the max number of characters is reached.
For example for a limit of 10 characters, the user can enter :
"1234567890"
or
"1 2 3 4 5 6 7 8 9 0"
You can measure the width of the typed input text with a Paint object:
EditText input = findViewById(R.id.imageDescriptionTextEdit) // Your EditText
final Paint paint = input.getPaint();
float textWidth = paint.measureText(input.getText().toString());
if (textWidth > input.getWidth()) {
// Prevent further input.
}
You can combine this check with a TextWatcher.

Edittext is not accepting number as input type

I cannot enter number (numeric) in the Edittext field.
If I keep android:inputType="text", number cannot be entered.
If I keep android:inputType="text|number", the keyboard accepts only digits.
But If I keep android:inputType="textMultiLine", I can enter both text/number but the first character cannot be number and it should be a character.
And I tried doing with other options too, nothing worked. I'm building the application with the target sdk:21
Note: I need both text / number as input
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++) {
if (!Character.isDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
your_edit_text.setFilters(new InputFilter[]{filter});
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
You can use
android:inputType="numberDecimal"
Try to not specify inputType or set it to "none" if you want to be able to enter text and numbers.

android EditText alphabet-only validation

i wanted to validate a EditText and see if all of the letters are alphabet. it should be able to handle multiple EditText. i need a way to prevent user from entering anything other then alphabet.
userTextInput=(EditText)findViewById(R.id.textInput);
userTextInput.addTextChangedListener(this);
public void afterTextChanged(Editable edit) {
String textFromEditView = edit.toString();
//first method
ArrayList[] ArrayList;
//ArrayList [] = new ArrayList;
for(int i=0; i<=textFromEditView.length(); i++)
{
if(textFromEditView[i].isLetter() == false)
{
edit.replace(0, edit.length(), "only alphabets");
}
}
//second method
try
{
boolean isOnlyAlphabet = textFromEditView.matches("/^[a-z]+$/i");
if(isOnlyAlphabet == false)
{
edit.replace(0, edit.length(), "only alphabets");
}
}
catch(NumberFormatException e){}
}
for my second method the moment i enter anything, number or alphabet, my app crash.
i have test my first method because it has the error textFromEditView must be an array type bue is resolved as string. can you help me to improve my code.
I think you'd do better using InputFilter:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned d, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetter(src.charAt(i))) {
return src.subSequence(start, i-1);
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
Code modified from: How do I use InputFilter to limit characters in an EditText in Android?
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
How to create EditText accepts Alphabets only in android?
You can set the inputType of the EditText. More Information here and here.

InputFilter on EditText cause repeating text

I'm trying to implement an EditText that limits input to Capital chars only [A-Z0-9] with digits as well.
I started with the InputFilter method from some post.But here I am getting one problem on Samsung Galaxy Tab 2 but not in emulator or Nexus 4.
Problem is like this :
When I type "A" the text shows as "A" its good
Now when I type "B" so text should be "AB" but it gives me "AAB"
this looks very Strange.
In short it repeats chars
Here's the code I'm working with this code :
public class DemoFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
int dend) {
if (source.equals("")) { // for backspace
return source;
}
if (source.toString().matches("[a-zA-Z0-9 ]*")) // put your constraints
// here
{
return source.toString().toUpperCase();
}
return "";
}
}
XML file code :
<EditText
android:id="#+id/et_licence_plate_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="0"
android:imeOptions="actionNext"
android:inputType="textNoSuggestions"
android:maxLength="3"
android:singleLine="true"
android:textSize="18px" >
</EditText>
I'm totally stuck up on this one, so any help here would be greatly appreciated.
The problem of characters duplication comes from InputFilter bad implementation. Rather return null if replacement should not change:
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, end, null, sp, 0);
return sp;
} else {
return sb;
}
}
}
private boolean isCharAllowed(char c) {
return Character.isUpperCase(c) || Character.isDigit(c);
}
I've run into the same issue, after fixing it with solutions posted here there was still a remaining issue with keyboards with autocomplete. One solution is to set the inputType as 'visiblePassword' but that's reducing functionality isn't it?
I was able to fix the solution by, when returning a non-null result in the filter() method, use the call
TextUtils.copySpansFrom((Spanned) source, start, newString.length(), null, newString, 0);
This copies the auto-complete spans into the new result and fixes the weird behaviour of repetition when selecting autocomplete suggestions.
I have found many bugs in the Android's InputFilter, I am not sure if those are bugs or intended to be so. But definitely it did not meet my requirements. So I chose to use TextWatcher instead of InputFilter
private String newStr = "";
myEditText.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) {
String str = s.toString();
if (str.isEmpty()) {
myEditText.append(newStr);
newStr = "";
} else if (!str.equals(newStr)) {
// Replace the regex as per requirement
newStr = str.replaceAll("[^A-Z0-9]", "");
myEditText.setText("");
}
}
#Override
public void afterTextChanged(Editable s) {
// Do nothing
}
});
The above code does not allow users to type any special symbol into your EditText. Only capital alphanumeric characters are allowed.
InputFilters can be attached to Editable S to constrain the changes that can be made to them.
Refer that it emphasises on changes made rather than whole text it contains..
Follow as mentioned below...
public class DemoFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
int dend) {
if (source.equals("")) { // for backspace
return source;
}
if (source.toString().matches("[a-zA-Z0-9 ]*")) // put your constraints
// here
{
char[] ch = new char[end - start];
TextUtils.getChars(source, start, end, ch, 0);
// make the characters uppercase
String retChar = new String(ch).toUpperCase();
return retChar;
}
return "";
}
}
The following solution also supports the option of an autocomplete keyboard
editTextFreeNote.addTextChangedListener( new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newStr = s.toString();
newStr = newStr.replaceAll( "[a-zA-Z0-9 ]*", "" );
if(!s.toString().equals( newStr )) {
editTextFreeNote.setText( newStr );
editTextFreeNote.setSelection(editTextFreeNote.getText().length());
}
}
#Override
public void afterTextChanged(Editable s) {}
} );
Same for me, InputFilter duplicates characters. This is what I've used:
Kotlin version:
private fun replaceInvalidCharacters(value: String) = value.replace("[a-zA-Z0-9 ]*".toRegex(), "")
textView.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun afterTextChanged(s: Editable) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val newValue = replaceInvalidCharacters(s.toString())
if (newValue != s.toString()) {
textView.setText(newValue)
textView.setSelection(textView.text.length)
}
}
})
works well.
try this:
class CustomInputFilter implements InputFilter {
StringBuilder sb = new StringBuilder();
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Log.d(TAG, "filter " + source + " " + start + " " + end + " dest " + dest + " " + dstart + " " + dend);
sb.setLength(0);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (Character.isUpperCase(c) || Character.isDigit(c) || c == ' ') {
sb.append(c);
} else
if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
}
}
return sb;
}
}
this also allows filtering when filter() method accepts multiple characters at once e.g. pasted text from a clipboard
I've met this problem few times before.
Setting some kinds of inputTypes in xml propably is the source of problem.
To resolve it without any additional logic in InputFilter or TextWatcher just set input type in code instead xml like this:
editText.setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
recently i faced same problem
reason of the problem is... if there is a no change in the input string then don't return source string return null, some device doesn't handle this properly that's why characters are repating.
in your code you are returning
return source.toString().toUpperCase();
don't return this , return null; in place of return source.toString().toUpperCase(); , but it will be a patch fix , it will not handle all scenarios , for all scenario you can use this code.
public class SpecialCharacterInputFilter implements InputFilter {
private static final String PATTERN = "[^A-Za-z0-9]";
// if you want to allow space use this pattern
//private static final String PATTERN = "[^A-Za-z\\s]";
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// Only keep characters that are letters and digits
String str = source.toString();
str = str.replaceAll(PATTERN, AppConstants.EMPTY_STRING);
return str.length() == source.length() ? null : str;
}
}
what is happening in this code , there is a regular expression by this we will find all characters except alphabets and digits , now it will replace all characters with empty string, then remaining string will have alphabets and digits.
The problem with most the answers here is that they all mess up the cursor position.
If you simply replace text, your cursor ends up in the wrong place for the next typed character
If you think you handled that by putting their cursor back at the end, well then they can't add prefix text or middle text, they are always jumped back to the end on each typed character, it's a bad experience.
You have an easy way to handle this, and a more universal way to handle it.
The easy way
<EditText
android:id="#+id/itemNameEditText"
android:text="#={viewModel.selectedCartItemModel.customName}"
android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
android:inputType="textVisiblePassword"/>
DONE!
Visible password will fix the issue of double callbacks and problems like that. Problem with this solution is it removes your suggestions and autocompletes, and things like that. So if you can get away with this direction, PLEASE DO!!! It will eliminate so many headaches of trying to handle every possible issue of the hard way lol.
The Hard Way
The issue is related to the inputfilter callback structure being triggered by autocomplete. It is easy to reproduce. Just set your inputType = text, and then type abc# you'll see it get called two times and if you can end up with abcabc instead of just abc if you were trying to ignore # for example.
First thing you have to handle is deleting to do this, you must
return null to accept "" as that is triggered by delete.
Second thing you have to handle is holding delete as that updates every so often, but can come in as a long string of characters, so you need to see if your text length shrunk before doing replacement text or you can end up duplicating your text while holding delete.
Third thing you need to handle is the duplicate callback, by keeping track of the previous text change call to avoid getting it twice. Don't worry you can still type the same letters back to back, it won't prevent that.
Here is my example. It's not perfect, and still has some kinks to work out, but it's a good place to start.
The following example is using databinding, but you are welcome to just use the intentFilter without databinding if that's your style. Abbreviated UI for showing only the parts that matter.
In this example, I restrict to alpha, numeric, and spaces only. I was able to cause a semi-colon to show up once while pounding on the android keyboard like crazy. So there is still some tweaking I believe that may need done.
DISCLAIMER
--I have not tested with auto complete
--I have not tested with suggestions
--I have not tested with copy/paste
--This solution is a 90% there solution to help you, not a battle tested solution
XML FILE
<layout
xmlns:bind="http://schemas.android.com/apk/res-auto"
>
<EditText
bind:allowAlphaNumericOnly="#{true}
OBJECT FILE
#JvmStatic
#BindingAdapter("allowAlphaNumericOnly")
fun restrictTextToAlphaNumericOnly(editText: EditText, value: Boolean) {
val tagMap = HashMap<String, String>()
val lastChange = "repeatCheck"
val lastKnownSize = "handleHoldingDelete"
if (value) {
val filter = InputFilter { source, start, end, dest, dstart, dend ->
val lastKnownChange = tagMap[lastChange]
val lastKnownLength = tagMap[lastKnownSize]?.toInt()?: 0
//handle delete
if (source.isEmpty() || editText.text.length < lastKnownLength) {
return#InputFilter null
}
//duplicate callback handling, Android OS issue
if (source.toString() == lastKnownChange) {
return#InputFilter ""
}
//handle characters that are not number, letter, or space
val sb = StringBuilder()
for (i in start until end) {
if (Character.isLetter(source[i]) || Character.isSpaceChar(source[i]) || Character.isDigit(source[i])) {
sb.append(source[i])
}
}
tagMap[lastChange] = source.toString()
tagMap[lastKnownSize] = editText.text.length.toString()
return#InputFilter sb.toString()
}
editText.filters = arrayOf(filter)
}
}

How to restrict the user did not enter more than two digits after decimal point?

I have edittext in listview. I want to restrict the user if they enter more than two digits after the decimal point. Now it allowing n number of numbers. How to restrict the user did not enter more than two numbers after decimal point without using pattern?
We can use a regular expression ( regex ) as follows:
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
To use it do:
editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
It might be late but i am posting my solution hope it will works for someone
in Your Text Watcher Method afterTextChanged do this .
public void afterTextChanged(Editable s) {
if(mEditText.getText().toString().contains(".")){
String temp[] = mEditText.getText().toString().split("\\.");
if(temp.length>1) {
if (temp[1].length() > 3) {
int length = mEditText.getText().length();
mEditText.getText().delete(length - 1, length);
}
}
}
}
You can use a TextWatcher and in the afterTextChanged method use a regular expression to match the required text and delete the extra numbers are they are entered.

Categories

Resources