Restrict special characters & space programmatically - android

I want to restrict user from entering special characters & space programmatically.
Below is my code
InputFilter[] alphaNumericFilter = new InputFilter[2];
alphaNumericFilter[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int k = start; k < end; k++) {
boolean isLetterOrDigit = Character.isLetterOrDigit(source.charAt(k));
boolean isSpaceChar = Character.isSpaceChar(source.charAt(k));
if ((source.length() > 0 && isSpaceChar) ||
(!isLetterOrDigit && !isSpaceChar) ||
(isSpaceChar && TextUtils.isEmpty(dest))) {
return "";
}
}
return null;
}
};
on pressing space it deleting last character.

Use this code to filter your edittext
private String yourCharacterThatYouWantToBlock= " ~#^|$%&*!";
private InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && yourCharacterThatYouWantToBlock.contains(("" + source))) {
return "";
}
return null;
}
};
Now apply this filter to your edittext.
yourEditText.setFilters(new InputFilter[] { filter });

You can do this way:
public static InputFilter getAlphaNumericInputFilter(){
return new InputFilter() {
#Override
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 ]+")){
return source;
}
return "";
}
};
}
Here If you can just changes matches string according to your requirement for eg. avoid space with alphanumeric then It should like this:[a-zA-Z0-9]+.
Hope It help you !

InputFilter alphaNumericFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5)
{
for (int k = arg1; k < arg2; k++) {
if (!Character.isLetterOrDigit(arg0.charAt(k))) {
return "";
}
}
return null;
}
};
mFirstName.setFilters(new InputFilter[]{ alphaNumericFilter});

Finally I have resolved this issue by adding below line in the code
mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
This line will not show suggestions on keyboard.

Related

How to limited EditText for start characters just english alphabet in Android

In my application I want use EditText and I want start characters just English alphabet.
My mean is, First of characters has just English alphabet (a to z).
I write below codes :
registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().length() < 2) {
registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if (src.toString().matches("[a-zA-Z ]+")) {
registerUsernameInptLay.setErrorEnabled(false);
return src;
}
registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
return "";
}
}});
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
}
});
But not work me! How can I it?
Please help me
Try this:
EditText et = findViewById(R.id.text_field);
// This part is to keep the existing filters of the EditText.
InputFilter[] filters = et.getFilters();
InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);
InputFilter firstFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && source.length() > 0 && dstart == 0){
if (!source.toString().matches("^[A-Za-z].*"))
return "";
}
return null;
}
};
// Add the filter to the array of filters
newFilters[newFilters.length - 1] = firstFilter;
et.setFilters(newFilters);
Can be simplified like this (if the previous InputFilter are not required)
EditText et = findViewById(R.id.text_field);
InputFilter firstFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && source.length() > 0 && dstart == 0){
if (!source.toString().matches("^[A-Za-z].*"))
return "";
}
return null;
}
};
et.setFilters(new InputFilter[]{firstFilter});
EDIT
If you want to keep the rest of the string (for example if the user pastes the text):
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && source.length() > 0 && dstart == 0) {
String s = source.toString();
if (!s.matches("^[A-Za-z].*")) {
Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
return s.substring(1, s.length());
}
}
return null;
}
EDIT 2
The above versions don't work on deletion or when a text is pasted with more than a forbidden char at the beginning (e.g. '88sdfs') as only the first one was removed and the rest kept.
This new version should cover all these cases.
I'd suggest to create a separated class for the InputFilter.
InputFilter firstFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (dstart != 0) { // The modified part is not beginning of the text
return null; // Nothing need to be changed
}
if (source.length() > 0) { // text is added
return onTextAdded(source.toString());
} else { // text is removed
return onTextRemoved(dest, dend);
}
}
private CharSequence onTextRemoved(Spanned dest, int dend) {
// check what the string will look like after the text being removed
String substring = dest.toString().substring(dend, dest.length());
// if there is still a string and it's not valid
if (substring.length() > 0 && !isValid(substring)) {
displayError();
// return the deleted part for the string to not change
return dest.subSequence(0, dend);
}
return null;
}
private String onTextAdded(String s) {
if (isValid(s)) {
return null;
} else {
String substring;
// We want to keep a part of the added string (it can be a paste).
// so we remove all the first characters as long as the string doesn't match
// the requirements
for (int i = 1; i < s.length(); i++) {
substring = s.substring(i, s.length());
if (isValid(substring))
break;
}
displayError();
return substring;
}
}
private boolean isValid(String s) {
return s.matches("^[A-Za-z].*");
}
private void displayError() {
Toast.makeText(getApplicationContext(), "This is a Toast", Toast.LENGTH_SHORT).show();
}
};
et.setFilters(new InputFilter[]{firstFilter});
Add this class to your project:
public class EnglishInputFilter implements InputFilter {
#Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int dstart, int dend) {
StringBuilder newChars = new StringBuilder(charSequence.toString().substring(start, end));
for (int i = 0; i < newChars.length(); ) {
if (!Character.isLetter(newChars.charAt(i)))
newChars.deleteCharAt(i);
else
i++;
}
return newChars.toString();
}
}
Then do this with your EditText:
myEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS)
myEditText.setFilters(new InputFilter[]{new EnglishInputFilter()});
It also removes no letter characters from pasted strings, if you paste "1A2B" it will really paste "AB"
You can add more filters, for example for limit the total length.
If you want that your edit text should accept starting first character with any English alphabet Then you can use regular expression like;
String regexp = "^([a-zA-Z]+).*$";
Pattern pattern = Pattern.compile(regexp);
boolean ismatches = pattern.matcher("your input that start with the alphabet").matches();
if(ismatches)
do your stuff
else
show error

Set InputFilter for white space and maximum length

I want to use Input filter where I can prevent first space entering AND max length of my edit text limited to 200 characters.
so far I have this:
Hot to I put the maxlength into the same filter
private void setInputFilterForEmailAndPwd(final EditText amountEditText) {
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.isSpace(source.charAt(i))) {
return "";
}
}
return null;
}
};
amountEditText.setFilters(new InputFilter[] { filter });
}
setInputFilterForEmailAndPwd(emailEdit);
I found the solution
I put new Input Filter, instead of setInputFilterForEmailAndPwd:
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.isWhitespace(source.charAt(i))) {
return "";
}
}
return null;
}
};
and then:
emailEdit.setFilters(new InputFilter[] { filter, new InputFilter.LengthFilter(200) });

disable white spaces using inputfilter - android

I am a beginner in android and I would like to disable white spaces in edittext using inputfilter.
How can I do that?
I found this code in the net:
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))) {
return "";
}
}
return null;
}
};
but it allows only letters and digits.
Thank you
Your code in a modified version:
InputFilter filter = new InputFilter()
{
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
{
for (int i = start; i < end; i++)
if (!Character.isLetter(source.charAt(i)) && !Character.isSpaceChar(source.charAt(i)))
return "";
return null;
}
};
myTextView.setFilters(new InputFilter[] { filter });
Code from SO-Thread Link

Android EditText Space Validation

I have an Edittext in my android application. I don't want to allow user to enter first space character..but after entering other charecter user can enter space also..I used
<EditText
android:id="#+id/editText1_in_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:digits="_,qwertzuiopasdfghjklyxcvbnm,QWERTYUIOPASDFGHJKLZXCVBNM,0123456789">
but in this case user can not enter space.
I have also used Text Watcher but I need not to allow user at the time of entering text as
android:digits works.
final EditText editText = (EditText)findViewById(R.id.editText1_in_row);
InputFilter filter = new InputFilter() {
boolean canEnterSpace = false;
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if(editText.getText().toString().equals(""))
{
canEnterSpace = false;
}
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char currentChar = source.charAt(i);
if (Character.isLetterOrDigit(currentChar) || currentChar == '_') {
builder.append(currentChar);
canEnterSpace = true;
}
if(Character.isWhitespace(currentChar) && canEnterSpace) {
builder.append(currentChar);
}
}
return builder.toString();
}
};
editText.setFilters(new InputFilter[]{filter});
and remove this property from your EditText
android:digits="_,qwertzuiopasdfghjklyxcvbnm,QWERTYUIOPASDFGHJKLZXCVBNM,0123456789"
This code works exactly according to your needs.
Using InputFilter easy to handle enter first white space character ignore
First setFilters() method on editText
editText.setFilters(new InputFilter[]{ignoreFirstWhiteSpace()});
Make InputFilter
// ignore enter First space on edittext
public InputFilter ignoreFirstWhiteSpace() {
return 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.isWhitespace(source.charAt(i))) {
if (dstart == 0)
return "";
}
}
return null;
}
};
}
No need to write android:digits property on XML
remove this line
android:digits="_,qwertzuiopasdfghjklyxcvbnm,QWERTYUIOPASDFGHJKLZXCVBNM,0123456789"
Simply restrict the user to type space as others said on start only:
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String text = createPL.getText().toString();
//restrict space for first char
if (text.startsWith(" ")) {
edittext.setText(text.trim());
}
}
Use this. If the character at starting Position is a space, set textView Text To blank
editText1_in_row.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length()>0 && s.subSequence(0, 1).toString().equalsIgnoreCase(" ")) {
editText1_in_row.setText(""); }
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This works for me
android:inputType="textPersonName"
android:digits= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-!##$%^*()"
why cant you use editText.getText().trim(); function while using the EditText data
If you want to filter input characters in your EditText, you need to use InputFilter. Here is example.
//Allow only letters or digits
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))) {
return "";
}
}
return null;
}
};
EditText text = (EditText)findViewById(R.id.edittext1);
text.setFilters(new InputFilter[]{filter});
For details look here
A slight variation on https://stackoverflow.com/users/2868352/abhishek-v answer.
public class NoInitialSpaceFilter implements InputFilter {
#Override
public CharSequence filter(final CharSequence source, final int start, final int end, final Spanned dest, final int dstart, final int dend) {
if (dstart == 0) {
for (int i = start; i < end; i++) {
if (Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
}
return null;
}
}
Usage:
editText.setFilters(new InputFilter[]{new NoInitialSpaceFilter});
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.,_-!##$()+=><:;?"
This is filter I have used for Name validation in EditText. First letter CAPS, not space and special character. After completing the word not allow more than a single space.
public void setNameFilter() {
InputFilter filter = new InputFilter() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (dend == 0) {
if (Character.isSpaceChar(source.charAt(i)) ||
!Character.isAlphabetic(source.charAt(i))) {
return Constants.Delimiter.BLANK;
} else {
return String.valueOf(source.charAt(i)).toUpperCase();
}
} else if (Character.isSpaceChar(source.charAt(i)) &&
String.valueOf(dest).endsWith(Constants.Delimiter.ONE_SPACE)) {
return Constants.Delimiter.BLANK;
} else if ((!Character.isSpaceChar(source.charAt(i)) &&
!Character.isAlphabetic(source.charAt(i)))) {
return Constants.Delimiter.BLANK;
}
}
return null;
}
};
editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(Constants.Length.NAME_LENGTH)});
}
here is kotlin extension
// ignore enter First space on edittext
fun EditText.filterFirstSpace() {
val initSpaceFilter: InputFilter = object : InputFilter {
var canEnterSpace = false
override fun filter(
source: CharSequence, start: Int, end: Int,
dest: Spanned, dstart: Int, dend: Int,
): CharSequence {
if (this#filterFirstSpace.text.toString() == "") {
canEnterSpace = false
}
val builder = StringBuilder()
for (i in start until end) {
val currentChar = source[i]
if (Character.isLetterOrDigit(currentChar) || currentChar == '_') {
builder.append(currentChar)
canEnterSpace = true
}
if (Character.isWhitespace(currentChar) && canEnterSpace) {
builder.append(currentChar)
}
}
return builder.toString()
}
}
filters = arrayOf(initSpaceFilter)
}

Disable specific keys on the keyboard

As you can disable certain keys on the keyboard to prevent the user to input wrong characters?
the following code is to disable numbers and chars
{
final InputFilter filter = new InputFilter() {
#Override
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))||Character.isLetter(source.charAt(i)))
{
return "";
}
}
return null;
}
};
answerTXT.setFilters(new InputFilter[]{filter});
}

Categories

Resources