Skip to content

Instantly share code, notes, and snippets.

@kiwiandroiddev
Last active October 1, 2021 09:22
Show Gist options
  • Save kiwiandroiddev/5c3b8d527aaf8b8318007fb685f23c5d to your computer and use it in GitHub Desktop.
Save kiwiandroiddev/5c3b8d527aaf8b8318007fb685f23c5d to your computer and use it in GitHub Desktop.
Android TextWatcher to restrict user input to match a given Regular Expression
/**
* Add this to (e.g.) an EditText via addTextChangedListener() to prevent any user input
* that doesn't match its supplied regex.
*
* Inspired by original Java code here: http://stackoverflow.com/a/11545229/1405990
*/
class RegexMaskTextWatcher(regexForInputToMatch : String) : TextWatcher {
private val regex = Pattern.compile(regexForInputToMatch)
private var previousText: String = ""
override fun afterTextChanged(s: Editable) {
if (regex.matcher(s).matches()) {
previousText = s.toString();
} else {
s.replace(0, s.length, previousText);
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment