Skip to content

Instantly share code, notes, and snippets.

@NaserKhoshfetrat
Created January 22, 2022 14:24
Show Gist options
  • Save NaserKhoshfetrat/b6273a1bfd692c5f1e553e73288fdd9f to your computer and use it in GitHub Desktop.
Save NaserKhoshfetrat/b6273a1bfd692c5f1e553e73288fdd9f to your computer and use it in GitHub Desktop.
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
class TextWatcherUtils {
fun mobilePhoneRequired(context: Context, editText: EditText): TextWatcher {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
if (s == null || s.isEmpty()) {
editText.error = context.getString(R.string.lblCompulsory)
} else {
val validationDto = validate(context, Validate.Mobile, s.toString())
if (!validationDto.isValid) {
editText.error = validationDto.errorMessage
} else {
editText.error = null
}
}
}
}
return textWatcher
}
fun nationalIdRequired(context: Context, editText: EditText): TextWatcher {
val textWatcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
if (s == null || s.isEmpty()) {
editText.error = context.getString(R.string.lblCompulsory)
} else {
val validationDto = validate(context, Validate.NationalId, s.toString())
if (!validationDto.isValid) {
editText.error = validationDto.errorMessage
} else {
editText.error = null
}
}
}
}
return textWatcher
}
fun separateThousands(context: Context, editText: EditText, groupingSeparator: Char, decimalSeparator: Char): TextWatcher {
val textWatcher = object : TextWatcher {
// editText.removeTextChangedListener(this)
private var busy = false
override fun afterTextChanged(s: Editable?) {
if (s == null || s.isEmpty()) {
editText.error = context.getString(R.string.lblCompulsory)
} else if (!busy) {
busy = true
var place = 0
val decimalPointIndex = s.indexOf(decimalSeparator)
var i = if (decimalPointIndex == -1) {
s.length - 1
} else {
decimalPointIndex - 1
}
while (i >= 0) {
val c = s[i]
if (c == groupingSeparator) {
s.delete(i, i + 1)
} else {
if (place % 3 == 0 && place != 0) {
// insert a comma to the left of every 3rd digit (counting from right to
// left) unless it's the leftmost digit
s.insert(i + 1, groupingSeparator.toString())
}
place++
}
i--
}
busy = false
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
return textWatcher
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment