How can i validate USSD code entered in edittext before sending
Here i put some code kindly help me.
ussd_edittext.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
ussd_edittext.setError("Invalid password");
ussd_ok.setEnabled(false);
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (ussd_edittext.getText().toString().trim().replaceAll("[^0-9#*]", "").length() < 4) {
ussd_edittext.setError("USSD code must contain * and #");
ussd_ok.setEnabled(false);
}
}
public void afterTextChanged(Editable s) {
Character cr = s.toString().charAt(0);
if(s.length() < 1)
{
if(!( (cr == '*') ) )
{ ussd_edittext.setError("USSD code must contain * and #");
ussd_ok.setEnabled(false);
}
else {
ussd_ok.setEnabled(true);
}
}
else
{
String lc = s.toString().substring(0, ussd_edittext.length() - 1);
if(!( (cr == '*') && lc.equals("#") ) )
{
ussd_edittext.setError("USSD code must contain * and #");
ussd_ok.setEnabled(false);
}
else {
ussd_ok.setEnabled(true);
}
}
}
});
i want to validate like it must contain * and # also 5 digits are minimum .
This might help:
if (Pattern.matches("(\\*[0-9]+[\\*[0-9]+]*#)", ussd_edittext.getText().toString()) && ussd_edittext.length() >= 5) {
//USSD code is valid
} else {
//USSD code is not valid
}
I had done something like this.
ussd_edittext.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
ussd_edittext.setError("Invalid password");
ussd_ok.setEnabled(false);
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (ussd_edittext.getText().toString().trim().length() < 4 && ( ! t.contains(""+ussd_edittext))) {
ussd_edittext.setError("USSD code must contain * and #");
ussd_ok.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s)
{
if (ussd_edittext.getText().toString().trim().length() > 4)
{
Character fc = ussd_edittext.getText().toString().charAt(0);
String lc = ussd_edittext.getText().toString().substring(ussd_edittext.length() - 1);
if(!((fc == '*') && lc.equals("#")))
{
ussd_edittext.setError("USSD code must contain * and #");
ussd_edittext.requestFocus();
}
else
{ ussd_ok.setEnabled(true); }
}
else
{ ussd_edittext.setError("USSD code must contain * and #"); }
}
});
Related
I want the user to type only letters in the first 5 characters and the next characters would only be numbers.
I've read the answer from this link: Validation allow only number and characters in edit text in android
However when I tried to do what I wanted to do, I'm getting error saying this:
java.lang.StringIndexOutOfBoundsException: length=1; index=1
at java.lang.String.charAt(Native Method)
The codes I've tried to do what I want.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start;i < etLettersAndNumbers.getText().length();i++) {
if (etLettersAndNumbers.getText().length() < 4) {
if (!Character.isLetter(source.charAt(i))) {
return "";
}
}
if (etLettersAndNumbers.getText().length() >= 4) {
if (!Character.isDigit(source.charAt(i))) {
return "";
}
}
}
return null;
}
};
etLettersAndNumbers.setFilters(new InputFilter[] {filter});
I'm using dynamic EditText.
try this:
public void set(final EditText etLettersAndNumbers) {
etLettersAndNumbers.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = etLettersAndNumbers.getText().toString();
char[] st = str.toCharArray();
try {
if (Character.isLetter(st[st.length - 1]) && st.length - 1 < 5) {
System.out.print("Nothing");
} else if (!Character.isLetter(st[st.length - 1]) && st.length - 1 < 5) {
if(count>0)
etLettersAndNumbers.setText("");
} else if (Character.isLetter(st[st.length - 1]) && st.length - 1 >= 5) {
if(count>0)
etLettersAndNumbers.setText("");
}
} catch (Exception e) {
e.getMessage();
}
}
});
}
I was implemented like after 4 digits hyphen display automatically like(2015-07) in edittext. my code works fine, but problem is while i delete before 4 digits value and again type it not working. addTextChangedListener not trigger when i edidtext retype like 2015-07 to 2014-07. But while i using "/" instead of "-" i can retype value. What is the problem?
mEdtProductionCode.addTextChangedListener(new TextWatcher() {
int prevL = 0;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
prevL = mEdtProductionCode.getText().toString().length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL < length) && length == 4) {
String data = mEdtProductionCode.getText().toString();
mEdtProductionCode.setText(data + "-");
mEdtProductionCode.setSelection(length + 1);
}
}
});
You should just move your character checking to the character after the fifth character has been entered, and then chop down String to put the custom character in between:
#Override
public void afterTextChanged(Editable s) {
int length = s.length();
if ((prevL <= length) && length == 5) {
String data = mEditProductionCode.getText().toString();
String beginData = data.substring(0,4);
String endData = Character.toString(data.charAt(length-1));
mEditProductionCode.setText(beginData + "-" + endData);
mEditProductionCode.setSelection(length + 1);
}
}
You can also use data.charAt(length-1) != '-' to check if user manually made dash input, in which case you just ignore and do not make changes to TextEdit.
edtTxt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if(s.length() != 0 && s.length() == 2){
String str = s.toString();
str.replaceAll("..(?!$)", "$0:");
edtTxt.setText(str);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
I need to display ":" after 2nd digit that is for example 10:25, maximum length is 5 digits it is edittext.
If i started typing in the edittext 10 after this ":" should be inserted then 10:25 should be displayed in the edittext.
I tried with the above logic not working. can anyone help me. Thanks in advance
After replaceAll you should assign the value to same variable. Its working fine..
public void afterTextChanged(Editable s) {
if(s.length() != 0 && s.length() == 3){
String str = s.toString();
str = str.replaceAll("..(?!$)", "$0:");
edtTxt.setText(str);
edtTxt.setSelection(edtTxt.getText().length()); //cursor at last position
}
}
First of all you ignore the result of str.replaceAll(). The method returns a String.
The if condition can be simplified to s.length() == 2.
And the regex you are using doesn't work.
This will add colon in the EditText after you have entered 2 characters
if (s.length() == 2) {
edtTxt.setText(s.toString() + ":");
}
Kotlin and improved version of the #sasikumar's solution:
private fun formatInput(clock: Editable?) {
if (clock.toString().isNotEmpty()
&& clock.toString().contains(":").not()
&& clock.toString().length == 3
) {
var str: String = clock.toString()
str = str.replace("..(?!$)".toRegex(), "$0:")
etClock.setText(str)
etClock.setSelection(etClock.text.length)
}
}
etClock.addTextChangedListener(
afterTextChanged = {
formatInput(it)
}
)
etClock.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
etClock.setSelection(etClock.text.length)
}
}
etClock.setOnClickListener {
etClock.setSelection(etClock.text.length)
}
And a great explanation of the used Regex: https://stackoverflow.com/a/23404646/421467
Just do it like this
editTextTime.addTextChangedListener {
if(it?.length == 3 && !it.contains(":")){
it.insert(2,":")
}
}
I think the code is clear
if you put 3 number it will add ":" before the 3rd number
and it will check if your 3rd Char it not already :
then it will insert ":" for you
How to delete two character at once with the filter?
I am trying to apply a simple filter to an EditText.
It must work as follows:
(want to receive format: 1234 5678....)
===> EDITED: First part works well.
1) when there are 4 digits in EditText and I am entering the 5-th digit -
first must appear a space and then this digit.
2) And I need a reverse for this (during characters deletion) -
the space must be deleted with the 5-th digit.
What is wrong with my code?
editText.setFilters(new InputFilter[]{new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// any chars except backspace
if (!source.equals("")) {
if (dest.length() == 4) {
// here I must add a space and then the source
// ===> EDITED:
return " " + source;
// return super.filter(" " + source, start, end + 1, dest, dstart, dend + 1);
} // backspace entered
} else {
if (dest.length() == 6) {
// here I must delete the 6-th character
// and the space before
return super.filter(source, 0, 0, dest, 5, 6);
}
}
return null;
}
}});
Please use this
public class CustomFormatWatcher implements TextWatcher {
private int size;
public CustomFormatWatcher(int size) {
this.size = size;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
char hyphen = ' ';
char c = 0;
if (editable.length() > 0) {
c = editable.charAt(editable.length() - 1);
if (c == hyphen) {
editable.delete(editable.length() - 1, editable.length());
}
}
if (editable.length() > 0 && (editable.length() % size) == 0) {
c = editable.charAt(editable.length() - 1);
if (hyphen == c) {
editable.delete(editable.length() - 1, editable.length());
}
}
if (editable.length() > 0 && (editable.length() % size) == 0) {
c = editable.charAt(editable.length() - 1);
// Only if its a digit where there should be a space we insert a hyphen
if (Character.isDigit(c) && TextUtils.split(editable.toString(), String.valueOf(hyphen)).length <= 3) {
editable.insert(editable.length() - 1, String.valueOf(hyphen));
}
}
}
}
and then use
myEditText.addTextChangedListener(new CustomFormatWatcher());
I suggest you to use TextWatcher to format your EditText input, because InputFilter is generally used for input restrictions, to decides what can be typed not to format the text.
You'll get your desired output with this code:
String mTextValue;
Character mLastChar = '\0'; // init with empty character
int mKeyDel;
myEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String eachBlock[] = myEditText.getText().toString().split(" ");
myEditText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
mKeyDel = 1;
return false;
}
});
if (mKeyDel == 0) {
if (((myEditText.getText().length() + 1) % 5) == 0) {
myEditText.setText(myEditText.getText() + " ");
myEditText.setSelection(myEditText.getText().length());
}
mTextValue = myEditText.getText().toString();
} else {
mTextValue = myEditText.getText().toString();
if (mLastChar.equals(' ')) {
mTextValue = mTextValue.substring(0, mTextValue.length() - 1);
myEditText.setText(mTextValue);
myEditText.setSelection(mTextValue.length());
}
mKeyDel = 0;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (s.length()>0) {// save the last char value
mLastChar = s.charAt(s.length() - 1);
} else {
mLastChar = '\0';
}
}
#Override
public void afterTextChanged(Editable s) {}
});
I am developing one application in android for California. now i want to enter Social Security Number in Edit Text in xxx-xx-xxxx format. i have tried following code for achieve the functionality but it is not working fine for clearing the text.. following is my code. any help would be appreciated. i want auto format functionality.
etSocialSecurityNumber.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = etSocialSecurityNumber.getText().toString();
textlength = etSocialSecurityNumber.getText().length();
if(text.endsWith(" "))
return;
if(textlength == 4 || textlength == 7 )
{
etSocialSecurityNumber.setText(new StringBuilder(text).insert(text.length()-1, "-").toString());
etSocialSecurityNumber.setSelection(etSocialSecurityNumber.getText().length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
This will add a - after every 4 characters and it handels all kind of editing of user, just put your condition for 3 and 2 chars:
edit_text.addTextChangedListener(new TextWatcher() {
private boolean spaceDeleted;
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = " ".equals(charDeleted.toString());
}
public void afterTextChanged(Editable editable) {
edit_text.removeTextChangedListener(this);
int cursorPosition = edit_text.getSelectionStart();
String withSpaces = formatText(editable);
edit_text.setText(withSpaces);
edit_text.setSelection(cursorPosition + (withSpaces.length() - editable.length()));
if (spaceDeleted) {
edit_text.setSelection(edit_text.getSelectionStart() - 1);
spaceDeleted = false;
}
edit_text.addTextChangedListener(this);
}
private String formatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
for (int i = 0; i < text.length(); ++i)
{
if (Character.isDigit(text.charAt(i)))
{
if (count % 4 == 0 && count > 0)
formatted.append("-");
formatted.append(text.charAt(i));
++count;
}
}
return formatted.toString();
}
});
Edited:
userNameET.addTextChangedListener(new TextWatcher() {
private boolean spaceDeleted;
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
CharSequence charDeleted = s.subSequence(start, start + count);
spaceDeleted = "-".equals(charDeleted.toString());
}
public void afterTextChanged(Editable editable) {
userNameET.removeTextChangedListener(this);
int cursorPosition = userNameET.getSelectionStart();
String withSpaces = formatText(editable);
userNameET.setText(withSpaces);
userNameET.setSelection(cursorPosition + (withSpaces.length() - editable.length()));
if (spaceDeleted) {
// userNameET.setSelection(userNameET.getSelectionStart() - 1);
spaceDeleted = false;
}
userNameET.addTextChangedListener(this);
}
private String formatText(CharSequence text)
{
StringBuilder formatted = new StringBuilder();
int count = 0;
if(text.length()==3||text.length()==6)
{
if (!spaceDeleted)
formatted.append(text+"-");
else
formatted.append(text);
}
else
formatted.append(text);
return formatted.toString();
}
});
The following Kotlin code sufficed my requirements
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
backspaced = count == 0
}
override fun afterTextChanged(s: Editable?) {
s?.apply {
if (!isEmpty()) {
if (get(lastIndex) != '-' && (length > 1 && get(lastIndex - 1) != '-') && !backspaced)
count { x -> x.isDigit() }.let { mapOf(3 to 3, 4 to 3, 5 to 6, 6 to 6)[it]?.let { index -> insert(index, "-") } }
else if ((get(lastIndex) == '-' && backspaced) || (lastIndexOf('-') in listOf(0,1,2,4,5,7,8,9,10)) )
delete(length - 1, length)
}
}
}
I know its too late to post an answer here. I just want to share the code which I used to format SSN. Try the following code.
public class SSNFormatter implements TextWatcher{
private boolean mFormatting;
private boolean clearFlag;
private int mLastStart;
private String mBeforeText;
private boolean spaceDeleted;
WeakReference<EditText> mWeakEditText;
public SSNFormatter(WeakReference<EditText> weakEditText) {
this.mWeakEditText = weakEditText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mLastStart = start;
mBeforeText = s.toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.length()>0 && mWeakEditText.get().getText().hashCode() == s.hashCode() && mWeakEditText.get().getError() != null)
mWeakEditText.get().setError(null);
if (!mFormatting) {
mFormatting = true;
int curPos = mLastStart;
String beforeValue = mBeforeText;
String currentValue = s.toString();
String formattedValue = formatSSN(s);
if (currentValue.length() > beforeValue.length()) {
int setCusorPos = formattedValue.length()
- (beforeValue.length() - curPos);
mWeakEditText.get().setSelection(
setCusorPos < 0 ? 0 : setCusorPos);
} else {
int setCusorPos = formattedValue.length()
- (currentValue.length() - curPos);
if (setCusorPos > 0
&& !Character.isDigit(formattedValue
.charAt(setCusorPos - 1))) {
setCusorPos--;
}
mWeakEditText.get().setSelection(
setCusorPos < 0 ? 0 : setCusorPos);
}
mFormatting = false;
}
}
private String formatSSN(Editable text){
StringBuilder formattedString = new StringBuilder();
// Remove everything except digits
int p = 0;
while (p < text.length()) {
char ch = text.charAt(p);
if (!Character.isDigit(ch)) {
text.delete(p, p + 1);
} else {
p++;
}
}
// Now only digits are remaining
String allDigitString = text.toString();
int totalDigitCount = allDigitString.length();
if (totalDigitCount == 0 || totalDigitCount > 10) {
// May be the total length of input length is greater than the
// expected value so we'll remove all formatting
text.clear();
text.append(allDigitString);
return allDigitString;
}
int alreadyPlacedDigitCount = 0;
// Only '1' is remaining and user pressed backspace and so we clear
// the edit text.
if (allDigitString.equals("1") && clearFlag) {
text.clear();
clearFlag = false;
return "";
}
boolean chang3 = true;
boolean chang2 = false;
// There must be a '-' inserted after the next 3 numbers
if (chang3 && totalDigitCount - alreadyPlacedDigitCount > 3) {
formattedString
.append(allDigitString.substring(alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 3) + "-");
alreadyPlacedDigitCount += 3;
chang3 = false;
chang2 = true;
}
// There must be a '-' inserted after the next 2 numbers
if (chang2 && totalDigitCount - alreadyPlacedDigitCount > 2) {
formattedString
.append(allDigitString.substring(alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 2) + "-");
alreadyPlacedDigitCount += 2;
chang3 = true;
chang2 = false;
}
// All the required formatting is done so we'll just copy the
// remaining digits.
if (totalDigitCount > alreadyPlacedDigitCount) {
formattedString.append(allDigitString
.substring(alreadyPlacedDigitCount));
}
text.clear();
text.append(formattedString.toString());
return formattedString.toString();
}
}