-
Notifications
You must be signed in to change notification settings - Fork 629
/
PostalCodeConfig.kt
80 lines (68 loc) · 2.7 KB
/
PostalCodeConfig.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.stripe.android.ui.core.elements
import androidx.annotation.StringRes
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.VisualTransformation
import kotlinx.coroutines.flow.MutableStateFlow
class PostalCodeConfig(
@StringRes override val label: Int,
override val capitalization: KeyboardCapitalization = KeyboardCapitalization.Words,
override val keyboard: KeyboardType = KeyboardType.Text,
override val trailingIcon: MutableStateFlow<TextFieldIcon?> = MutableStateFlow(null),
country: String
) : TextFieldConfig {
override val debugLabel: String = "postal_code_text"
override val visualTransformation: VisualTransformation? = null
override val loading: MutableStateFlow<Boolean> = MutableStateFlow(false)
private val format = CountryPostalFormat.forCountry(country)
override fun determineState(input: String): TextFieldState = object : TextFieldState {
override fun shouldShowError(hasFocus: Boolean) = false
override fun isValid(): Boolean {
return input.length in format.minimumLength..format.maximumLength &&
input.matches(format.regexPattern)
}
override fun getError(): FieldError? = null
override fun isFull(): Boolean = input.length >= format.minimumLength
override fun isBlank(): Boolean = input.isBlank()
}
override fun filter(userTyped: String): String =
if (
setOf(KeyboardType.Number, KeyboardType.NumberPassword).contains(keyboard)
) {
userTyped.filter { it.isDigit() }
} else {
userTyped
}.replace(Regex("\\s*"), "")
override fun convertToRaw(displayName: String) = displayName
override fun convertFromRaw(rawValue: String) = rawValue
sealed class CountryPostalFormat(
val minimumLength: Int,
val maximumLength: Int,
val regexPattern: Regex
) {
object CA : CountryPostalFormat(
minimumLength = 6,
maximumLength = 6,
regexPattern = Regex("([a-zA-Z]\\d)+")
)
object US : CountryPostalFormat(
minimumLength = 5,
maximumLength = 9,
regexPattern = Regex("\\d+")
)
object Other : CountryPostalFormat(
minimumLength = 4,
maximumLength = 12,
regexPattern = Regex(".+")
)
companion object {
fun forCountry(country: String): CountryPostalFormat {
return when (country) {
"US" -> US
"CA" -> CA
else -> Other
}
}
}
}
}