Last active
October 1, 2021 09:22
-
-
Save kiwiandroiddev/5c3b8d527aaf8b8318007fb685f23c5d to your computer and use it in GitHub Desktop.
Android TextWatcher to restrict user input to match a given Regular Expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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