Skip to content

Commit

Permalink
add phone number validation check
Browse files Browse the repository at this point in the history
  • Loading branch information
ibrahimsn98 committed Dec 1, 2020
1 parent eb8cdad commit 34762ad
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/src/main/java/me/ibrahimsn/lib/PhoneNumberKit.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import android.graphics.drawable.Drawable
import android.text.InputFilter
import android.text.InputType
import android.util.Patterns
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.textfield.TextInputLayout
Expand All @@ -30,6 +31,8 @@ class PhoneNumberKit(private val context: Context) {

private var hasManualCountry = false

private var specialLength = 0

private var rawInput: CharSequence?
get() = input?.editText?.text
set(value) {
Expand All @@ -39,6 +42,8 @@ class PhoneNumberKit(private val context: Context) {
input?.tag = null
}

val isValid: Boolean get() = validate(rawInput)

private val textWatcher = object : PhoneNumberTextWatcher() {
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
if (input?.tag != Constants.VIEW_TAG) {
Expand Down Expand Up @@ -100,7 +105,6 @@ class PhoneNumberKit(private val context: Context) {

// Set text length limit according to the example phone number
core.getExampleNumber(country.iso2)?.let { example ->

if (isManual) {
hasManualCountry = true
rawInput = if (country.countryCode != example.countryCode) {
Expand All @@ -113,6 +117,7 @@ class PhoneNumberKit(private val context: Context) {

core.formatPhoneNumber(core.getExampleNumber(country.iso2))?.let { number ->
input?.editText?.filters = arrayOf(InputFilter.LengthFilter(number.length))
specialLength = number.length
format = createNumberFormat(number)
applyFormat()
}
Expand Down Expand Up @@ -260,4 +265,11 @@ class PhoneNumberKit(private val context: Context) {
}
return null
}

private fun validate(number: CharSequence?): Boolean {
if (number == null) return false
return !number.isNullOrEmpty()
&& number.length >= specialLength
&& Patterns.PHONE.matcher(number).find()
}
}

0 comments on commit 34762ad

Please sign in to comment.