Skip to content

Commit

Permalink
Fix crash on special characters input
Browse files Browse the repository at this point in the history
  • Loading branch information
AnasNaouchi committed Oct 29, 2023
1 parent a515a4c commit 3bff054
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
13 changes: 12 additions & 1 deletion sdk/src/main/java/co/omise/android/ui/ExpiryDateEditText.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import android.util.AttributeSet
import co.omise.android.extensions.disableOptions
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
* ExpiryDateEditText is a custom EditText for credit card expiration date field. This EditText
Expand Down Expand Up @@ -37,7 +39,7 @@ class ExpiryDateEditText : OmiseEditText {
addTextChangedListener(textWatcher)
disableOptions()
filters = arrayOf(InputFilter.LengthFilter(MAX_CHARS))
inputType = InputType.TYPE_CLASS_PHONE
inputType = InputType.TYPE_CLASS_NUMBER
}

override fun onSelectionChanged(selStart: Int, selEnd: Int) {
Expand Down Expand Up @@ -73,6 +75,15 @@ class ExpiryDateEditText : OmiseEditText {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s == null || s.length > MAX_CHARS) return

// Define a regular expression pattern to match non-numeric characters and DATE_SEPARATOR
val pattern: Pattern = Pattern.compile("[^0-9" + Pattern.quote(DATE_SEPARATOR) + "]")

// Use a Matcher to find any non-numeric characters in the string
val matcher: Matcher = pattern.matcher(s)
if(matcher.find()){
return
}

// On deleting
if (s.length < beforeChangedText.length) {
if (beforeChangedText[beforeChangedText.length - 1].toString() == DATE_SEPARATOR) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ class ExpiryDateEditTextTest {
assertEquals(Unit, editText.validate())
}

@Test
fun validate_ignoreSpecialCharactersInput() {
"*,.".forEach { editText.append(it.toString()) }

assertEquals("", editText.text.toString())
"1234".forEach { editText.append(it.toString()) } // 12/34
assertEquals("12/34", editText.text.toString())
}

@Test(expected = InputValidationException.EmptyInputException::class)
fun validate_emptyValue() {
"".forEach { editText.append(it.toString()) }
Expand Down

0 comments on commit 3bff054

Please sign in to comment.