Created
August 29, 2019 13:17
-
-
Save hitesh-dhamshaniya/78b7ca13dd102404ec28878f0f0fd972 to your computer and use it in GitHub Desktop.
Kotlin Validation manager class, it will help to easy check validation
This file contains 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
package com.devdigital.eztp.utils.validator | |
import com.devdigital.eztp.extensions.getTrimString | |
import com.google.android.material.textfield.TextInputLayout | |
import kotlinx.android.synthetic.main.component_edittext.view.* | |
import java.util.regex.Pattern | |
/** | |
* @author Hitesh | |
* @version 1.0 | |
* @since 29-08-2019 | |
*/ | |
class ValidationManager { | |
private val mValidationFields = ArrayList<ValidationField>() | |
fun addField(field: ValidationField): ValidationManager { | |
mValidationFields.add(field) | |
return this | |
} | |
fun validate():Boolean{ | |
var status = true | |
for (field in mValidationFields) { | |
val status1 = when(field.type){ | |
ValidationType.EMAIL->{ | |
Validator.email(field) | |
} | |
else->{ | |
Validator.text(field) | |
} | |
} | |
if(!status1){ | |
status = false | |
} | |
} | |
return status | |
} | |
} | |
object Validator{ | |
fun email(field: ValidationField) : Boolean { | |
val text = field.view.editText?.getTrimString() | |
when{ | |
text.isNullOrBlank()->{ | |
field.view.error = field.emptyMessage?:field.message | |
} | |
!isEmailValid(text)->{ | |
field.view.error = field.message | |
} | |
else-> return true | |
} | |
return false | |
} | |
fun text(field: ValidationField) : Boolean { | |
val text = field.view.editText?.getTrimString() | |
when{ | |
text.isNullOrBlank() ->{ | |
field.view.inputLayout?.error = field.emptyMessage?:field.message | |
} | |
else-> return true | |
} | |
return false | |
} | |
private fun isEmailValid(email: String): Boolean { | |
return Pattern.compile( | |
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]|[\\w-]{2,}))@" | |
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" | |
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\." | |
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?" | |
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9]))|" | |
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$" | |
).matcher(email).matches() | |
} | |
} | |
data class ValidationField( | |
val view: TextInputLayout, | |
val message:String, | |
val emptyMessage:String? = null, | |
val type: ValidationType = ValidationType.TEXT | |
) | |
enum class ValidationType { | |
EMAIL, | |
PHONE, | |
TEXT | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment