--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/AlphaValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | class AlphaValidator(errorMessage: String) : PatternValidator(errorMessage, "[A-z\u00C0-\u00ff \\./-\\?]*")
4 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/bg_round_corners.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed May 19 17:29:13 EET 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | .DS_Store
4 |
5 | /local.properties
6 | /.idea/workspace.xml
7 | /.idea/libraries
8 | .idea
9 |
10 |
11 | /build
12 | /*/build/
13 | build
14 |
15 | /captures
16 | .externalNativeBuild
17 |
18 | *.apk
19 | *.aab
20 |
21 | app/release
22 | app/debug
23 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/Validatable.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | /**
4 | * The interface that every field must implement to be validated
5 | * return true if valid, false otherwise.
6 | */
7 | interface Validatable {
8 | fun validate(): Boolean
9 | }
10 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/AlphaNumericValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 |
4 | class AlphaNumericValidator(errorMessage: String):
5 | PatternValidator(errorMessage, "[a-zA-Z0-9\u00C0-\u00FF \\./-\\?]*")
6 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/DomainValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import androidx.core.util.PatternsCompat
4 |
5 | class DomainValidator(errorMessage: String) : PatternValidator(errorMessage, PatternsCompat.DOMAIN_NAME)
6 |
--------------------------------------------------------------------------------
/core/src/main/res/anim/shake_error.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/core/src/main/res/xml/settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
--------------------------------------------------------------------------------
/rxjava/src/main/res/anim/shake_error.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/TextViewValidators.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import com.sha.formvalidator.textview.validator.CustomValidator
4 | import java.util.*
5 |
6 | object TextViewValidators {
7 | var customValidators: List = ArrayList()
8 | }
9 |
--------------------------------------------------------------------------------
/rxjava/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: Plugins.androidLibrary
2 | apply from: "$rootDir/${GradleName.common}"
3 | apply plugin: Plugins.kotlinAndroid
4 | apply plugin: Plugins.kotlinAndroidExtensions
5 | apply plugin: Plugins.dcendents
6 |
7 | dependencies {
8 | api project(path: ':core')
9 | api Deps.rxJava
10 | }
11 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 |
2 | ## Version 2.0.0
3 |
4 | - [ ] Form: widgets wrapper for triggering validation with single click.
5 | - [ ] Kotlin migration.
6 | - [ ] Unit testing.
7 | - [ ] Separate module for RxJava.
8 |
9 | ## Version 2.2.0
10 | - [ ] Allow hiding the error message in case the error message displaying is disabled.
11 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/CustomValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | import android.content.Context
4 |
5 | abstract class CustomValidator(errorMessage: String) : TextValidator(errorMessage) {
6 | abstract fun customValidationType(context: Context): String
7 | }
8 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/PersonNameValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | class PersonNameValidator(errorMessage: String)// will allow people with hyphens in his name or surname. Supports also unicode
4 | : PatternValidator(errorMessage, "[\\p{L}-]+")
5 |
--------------------------------------------------------------------------------
/fastlane/report.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/DummyValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * This is a dummy validator. It just returns true on each input.
5 | *
6 | */
7 | class DummyValidator : TextValidator("") {
8 | override fun isValid(text: String): Boolean = true
9 | }
10 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/PersonFullNameValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | class PersonFullNameValidator(errorMessage: String)// will allow people with hyphens in his name or surname. Supports also unicode
4 | : PatternValidator(errorMessage, "[\\p{L}- ]+")
5 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_examples.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/OnOffValidation.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model
2 |
3 | enum class OnOffValidation constructor(var value: Int) {
4 | ON(0),
5 | OFF(1);
6 |
7 | companion object {
8 | fun fromValue(value: Int?): OnOffValidation = values().firstOrNull { it.value == value } ?: ON
9 | }
10 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/RequiredValidation.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model
2 |
3 | enum class RequiredValidation constructor(var value: Int) {
4 | REQUIRED(0),
5 | NOT_REQUIRED(1);
6 |
7 | companion object {
8 | fun fromValue(value: Int?) = values().firstOrNull { it.value == value } ?: REQUIRED
9 | }
10 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_alpha.xml:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_date.xml:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_personname.xml:
--------------------------------------------------------------------------------
1 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_personfullname.xml:
--------------------------------------------------------------------------------
1 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/CheckedValidation.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model
2 |
3 | enum class CheckedValidation constructor(var value: Int) {
4 | CHECKED(0),
5 | UNCHECKED(1);
6 |
7 | companion object {
8 | fun fromValue(value: Int?): CheckedValidation = values().firstOrNull { it.value == value } ?: CHECKED
9 | }
10 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/WebUrlValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import android.util.Patterns
4 |
5 | /**
6 | * Validates a web url in the format:
7 | * scheme + authority + path
8 | *
9 | */
10 | class WebUrlValidator(errorMessage: String) : PatternValidator(errorMessage, Patterns.WEB_URL)
11 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_date_custom.xml:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/IpAddressValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import android.util.Patterns
4 |
5 | /**
6 | * Validates the ipaddress. The regexp was taken from the android source code.
7 | *
8 | */
9 | class IpAddressValidator(errorMessage: String) : PatternValidator(errorMessage, Patterns.IP_ADDRESS)
10 |
--------------------------------------------------------------------------------
/sample/src/main/res/menu/styling_options_menu.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_ip_address.xml:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_domain_name.xml:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/item_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/SuffixValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the input field contains only numbers.
5 | *
6 | */
7 | class SuffixValidator(private val suffix: String, errorMessage: String) : TextValidator(errorMessage) {
8 | override fun isValid(text: String): Boolean = text.endsWith(suffix)
9 | }
10 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_phone.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/RequiredValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A simple validator that validates the field only if the field is not empty.
5 | *
6 | */
7 | class RequiredValidator(errorMessage: String = "") : TextValidator(errorMessage) {
8 |
9 | override fun isValid(text: String): Boolean = text.trim { it <= ' ' }.isNotEmpty()
10 | }
11 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/PrefixValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the input field contains only numbers.
5 | *
6 | */
7 | class PrefixValidator(private val prefix: String, errorMessage: String) : TextValidator(errorMessage) {
8 |
9 | override fun isValid(text: String): Boolean = text.startsWith(prefix)
10 | }
11 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_email.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_creditcard.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_weburl.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_no_check.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_regex.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_email_or_creditcard.xml:
--------------------------------------------------------------------------------
1 |
9 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/PhoneValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import android.util.Patterns
4 |
5 | /**
6 | * It validates phone numbers.
7 | * Regexp was taken from the android source code.
8 | */
9 | class PhoneValidator(errorMessage: String)
10 | // sdd = space, dot, or dash
11 | // +*
12 | // ()*
13 | : PatternValidator(errorMessage, Patterns.PHONE)
14 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_numeric.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_allowempty.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/NumberOneCustomValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import android.content.Context
4 | import com.sha.formvalidator.textview.validator.CustomValidator
5 |
6 | class NumberOneCustomValidator(errorMessage: String) : CustomValidator(errorMessage) {
7 | override fun customValidationType(context: Context): String {
8 | return "Num1"
9 | }
10 | override fun isValid(text: String) = text == "1"
11 | }
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: Plugins.androidApplication
2 | apply from: "$rootDir/${GradleName.common}"
3 | apply plugin: Plugins.kotlinAndroid
4 | apply plugin: Plugins.kotlinAndroidExtensions
5 |
6 | dependencies {
7 | implementation project(Lib.core)
8 | implementation project(Lib.rxJava)
9 |
10 | implementation Deps.androidx_appCompat
11 | implementation Deps.android_material
12 | implementation Deps.androidx_core_ktx
13 | implementation Deps.multidex
14 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/App.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample
2 |
3 | import android.app.Application
4 | import com.sha.formvalidator.textview.TextViewValidators
5 | import com.sha.formvalidatorsample.validator.NumberOneCustomValidator
6 |
7 | class App : Application() {
8 | override fun onCreate() {
9 | super.onCreate()
10 | TextViewValidators.customValidators = listOf(NumberOneCustomValidator("Value doesn't equal 1"))
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/InverseValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * It's a validator that applies the "NOT" logical operator to the validator it wraps.
5 | *
6 | */
7 | class InverseValidator(validator: TextValidator, errorMessage: String = "") : TextValidator(errorMessage) {
8 | private var v: TextValidator = validator
9 |
10 | override fun isValid(text: String): Boolean = !v.isValid(text)
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_custom_validation_type.xml:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/helper/AnimationHelper.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model.helper
2 |
3 | import android.view.View
4 | import android.view.animation.AnimationUtils
5 | import com.sha.formvalidator.R
6 |
7 | internal object AnimationHelper {
8 |
9 | fun error(v: View) {
10 | v.startAnimation(
11 | AnimationUtils.loadAnimation(
12 | v.context,
13 | R.anim.shake_error)
14 | )
15 | }
16 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/ValueMatchValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A simple validator that validates the field only if the value is the same as another one.
5 | *
6 | */
7 | class ValueMatchValidator(errorMessage: String, vararg texts: String) : TextValidator(errorMessage) {
8 | private val tvs: List = listOf(*texts)
9 |
10 | override fun isValid(text: String): Boolean = tvs.all { it == text }
11 | }
12 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/LengthRangeValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the text is within the given range.
5 | *
6 | */
7 | class LengthRangeValidator(errorMessage: String, private val min: Int, private val max: Int) : TextValidator(errorMessage) {
8 |
9 | override fun isValid(text: String): Boolean {
10 | val length = text.length
11 | return length in min..max
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | @color/black
4 | @color/black
5 | #fcbf10
6 | #E6AE0E
7 | @color/yellow
8 | #F4A890
9 | #000
10 | #fff
11 | #545554
12 |
13 |
14 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/EmailValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import android.util.Patterns
4 |
5 | /**
6 | * This validates an email using regexps.
7 | * Note that if an email passes the validation with this validator it doesn't mean it's a valid email - it means it's a valid email format
8 | *
9 | */
10 | class EmailValidator(errorMessage: String = "") : PatternValidator(errorMessage, Patterns.EMAIL_ADDRESS) {
11 | }
12 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_float_numeric_range.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_phone_custommessages.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/validator/NumberOneCustomValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.validator
2 |
3 | import android.content.Context
4 | import com.sha.formvalidator.textview.validator.CustomValidator
5 | import com.sha.formvalidatorsample.R
6 |
7 | class NumberOneCustomValidator(errorMessage: String) : CustomValidator(errorMessage) {
8 | override fun customValidationType(context: Context): String {
9 | return context.getString(R.string.custom_validator_number_one)
10 | }
11 | override fun isValid(text: String) = text == "1"
12 | }
13 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/field_alpha_textinputlayout.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
12 |
13 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/CustomValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import org.junit.Before
5 | import org.junit.Test
6 |
7 | class CustomValidatorTest {
8 | lateinit var validator: TextValidator
9 |
10 | @Before
11 | fun setup() {
12 | validator = NumberOneCustomValidator("Invalid!")
13 | }
14 |
15 | @Test
16 | fun validate_valid() {
17 | assert(validator.isValid("1"))
18 | }
19 |
20 | @Test
21 | fun validate_invalid() {
22 | assert(!validator.isValid("2"))
23 | }
24 | }
--------------------------------------------------------------------------------
/core/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: Plugins.androidLibrary
2 | apply from: "$rootDir/${GradleName.common}"
3 | apply plugin: Plugins.kotlinAndroid
4 | apply plugin: Plugins.kotlinAndroidExtensions
5 | apply plugin: Plugins.dcendents
6 |
7 | dependencies {
8 | implementation Deps.androidx_appCompat
9 | implementation Deps.androidx_preference
10 | implementation Deps.android_material
11 | implementation Deps.androidx_core_ktx
12 |
13 | testImplementation TestDeps.junit
14 | testImplementation TestDeps.androidx_junit
15 | testImplementation TestDeps.androidx_espressoCore
16 | testImplementation TestDeps.androidx_test_core_ktx
17 | }
18 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/TextValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | import android.widget.TextView
4 |
5 | /**
6 | * Validator abstract class. To be used with FormEditText
7 | *
8 | */
9 | abstract class TextValidator(var errorMessage: String = "") {
10 |
11 | /**
12 | * Should check if the [TextView] is valid.
13 | *
14 | * @param text the [TextView] under evaluation
15 | * @return true if the edittext is valid, false otherwise
16 | */
17 | abstract fun isValid(text: String): Boolean
18 |
19 | fun hasErrorMessage(): Boolean = errorMessage.isNotEmpty()
20 | }
21 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/composite/CompositeValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.composite
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 |
5 | /**
6 | * Abstract class for a multi-validator.
7 | *
8 | * @see AndValidator
9 | *
10 | * @see OrValidator
11 | */
12 | abstract class CompositeValidator(message: String, vararg validators: TextValidator) : TextValidator(message) {
13 | protected val validators: MutableList = mutableListOf(*validators)
14 |
15 | fun enqueue(newValidator: TextValidator) {
16 | validators.add(newValidator)
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/FloatNumericRangeValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the input field contains only numbers
5 | * and the number is within the given range.
6 | *
7 | * @author Said Tahsin Dane @gmail.com>
8 | */
9 | class FloatNumericRangeValidator(errorMessage: String, private val floatMin: Double, private val floatMax: Double) : TextValidator(errorMessage) {
10 | override fun isValid(text: String): Boolean {
11 | return try { text.toDouble() in floatMin..floatMax }
12 | catch (e: NumberFormatException) { false }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/DummyValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.DummyValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class DummyValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = DummyValidator()
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("kkkkk"))
19 | }
20 |
21 | @Test
22 | fun validate_validIfEmpty() {
23 | assert(validator.isValid(""))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/NumericRangeValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the input field contains only numbers
5 | * and the number is within the given range.
6 | *
7 | */
8 | class NumericRangeValidator(errorMessage: String, private val min: Long, private val max: Long) : TextValidator(errorMessage) {
9 |
10 | override fun isValid(text: String): Boolean {
11 | return try {
12 | val value = java.lang.Long.parseLong(text)
13 | value in min..max
14 | } catch (e: NumberFormatException) {
15 | false
16 | }
17 |
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/PrefixValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.PrefixValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class PrefixValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = PrefixValidator("prefix", "Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("prefixXX"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/SuffixValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.SuffixValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class SuffixValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = SuffixValidator("suffix", "Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("XXsuffix"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/RequiredValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.RequiredValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class RequiredValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = RequiredValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("378734493671000"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid(""))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/pattern/AlphaValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.AlphaValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class AlphaValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = AlphaValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("rrlll"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11*%"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/CreditCardValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.CreditCardValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class CreditCardValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = CreditCardValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("378734493671000"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/LengthRangeValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.LengthRangeValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class LengthRangeValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = LengthRangeValidator("Invalid!", 1, 5)
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("1"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("123456"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/pattern/DomainValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.DomainValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class DomainValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = DomainValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("www.google.com"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/troy379/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/NumericLengthRangeValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.NumericRangeValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class NumericLengthRangeValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = NumericRangeValidator("Invalid!", 1, 5)
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("1"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("6"))
24 | }
25 | }
--------------------------------------------------------------------------------
/rxjava/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/troy379/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/troy379/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/AlphaNumericValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.AlphaNumericValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class AlphaNumericValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = AlphaNumericValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("rr378734493671000"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11*%"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/pattern/PersonNameValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.PersonNameValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class PersonNameValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = PersonNameValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("Shaban"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("Shaban 123"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/pattern/AlphaNumericValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.AlphaNumericValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class AlphaNumericValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = AlphaNumericValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("rrlll2233"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("11*%"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/FloatNumericLengthRangeValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.FloatNumericRangeValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class FloatNumericLengthRangeValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = FloatNumericRangeValidator("Invalid!", 1.0, 5.0)
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("1"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("6"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/pattern/PersonFullNameValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.pattern.PersonFullNameValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class PersonFullNameValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = PersonFullNameValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("Shaban Kamel"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | assert(!validator.isValid("Shaban 123"))
24 | }
25 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/TextViewValidationType.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | enum class TextViewValidationType constructor(var value: Int) {
4 | REGEX(0),
5 | NUMERIC(1),
6 | ALPHA(2),
7 | ALPHA_NUMERIC(3),
8 | EMAIL(4),
9 | CREDIT_CARD(5),
10 | PHONE(6),
11 | DOMAIN_NAME(7),
12 | IP_ADDRESS(8),
13 | WEB_URL(9),
14 | NOT_EMPTY(10),
15 | PERSON_NAME(11),
16 | PERSON_FULL_NAME(12),
17 | DATE(13),
18 | NUMERIC_RANGE(14),
19 | FLOAT_NUMERIC_RANGE(15),
20 | NOT_DETECTABLE(2000);
21 |
22 | companion object {
23 | fun fromValue(value: Int): TextViewValidationType {
24 | return values().firstOrNull { it.value == value } ?: NOT_DETECTABLE
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/InverseValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.CreditCardValidator
4 | import com.sha.formvalidator.textview.validator.InverseValidator
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 | import org.junit.Before
7 | import org.junit.Test
8 |
9 | class InverseValidatorTest {
10 | lateinit var validator: TextValidator
11 |
12 | @Before
13 | fun setup() {
14 | validator = InverseValidator(CreditCardValidator(), "Invalid!")
15 | }
16 |
17 | @Test
18 | fun validate_valid() {
19 | assert(validator.isValid("11"))
20 | }
21 |
22 | @Test
23 | fun validate_invalid() {
24 | assert(!validator.isValid("378734493671000"))
25 | }
26 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.content.Intent
5 | import android.os.Bundle
6 | import android.view.View
7 |
8 | import com.sha.formvalidatorsample.R
9 |
10 | class MainActivity : Activity() {
11 |
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | setContentView(R.layout.activity_main)
15 |
16 | findViewById(R.id.btnFields).setOnClickListener { show(FieldsActivity::class.java) }
17 | findViewById(R.id.btnForm).setOnClickListener { show(FormActivity::class.java) }
18 | }
19 |
20 | private fun show(clazz: Class<*>) = startActivity(Intent(this, clazz))
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/NumericValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.NumericValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class NumericValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = NumericValidator("Invalid!")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("1"))
19 | }
20 |
21 | @Test
22 | fun validate_invalidIfWrong() {
23 | assert(!validator.isValid("6f"))
24 | }
25 |
26 | @Test
27 | fun validate_invalidIfEmpty() {
28 | assert(!validator.isValid(""))
29 | }
30 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/ValueMatchValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 | import com.sha.formvalidator.textview.validator.ValueMatchValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class ValueMatchValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | }
14 |
15 | @Test
16 | fun validate_valid() {
17 | validator = ValueMatchValidator("Invalid!", "378734493671000")
18 | assert(validator.isValid("378734493671000"))
19 | }
20 |
21 | @Test
22 | fun validate_invalid() {
23 | validator = ValueMatchValidator("Invalid!", "11")
24 | assert(!validator.isValid("378734493671000"))
25 | }
26 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/DateValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.DateValidator
4 | import com.sha.formvalidator.textview.validator.TextValidator
5 | import org.junit.Before
6 | import org.junit.Test
7 |
8 | class DateValidatorTest {
9 | lateinit var validator: TextValidator
10 |
11 | @Before
12 | fun setup() {
13 | validator = DateValidator("Invalid!", "YYYY:MM:DD")
14 | }
15 |
16 | @Test
17 | fun validate_valid() {
18 | assert(validator.isValid("2019:12:14"))
19 | }
20 |
21 | @Test
22 | fun validate_invalidIfWrong() {
23 | assert(!validator.isValid("2019"))
24 | }
25 |
26 | @Test
27 | fun validate_invalidIfEmpty() {
28 | assert(!validator.isValid(""))
29 | }
30 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/composite/OrValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.composite
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 |
5 | /**
6 | * The or validator checks if one of passed validators is returning true.
7 | * Validator's priority is maintained by index, the lower index is the higher priority.
8 | * Note: the message that will be shown is the one passed to the Constructor
9 | *
10 | */
11 | class OrValidator(message: String, vararg validators: TextValidator) : CompositeValidator(message, *validators) {
12 |
13 | override fun isValid(text: String): Boolean {
14 | for (v in validators)
15 | if (v.isValid(text)) return true // Remember :) We're acting like an || operator.
16 |
17 | return false
18 | }
19 |
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/pattern/PatternValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.pattern
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 |
5 | import java.util.regex.Pattern
6 |
7 | /**
8 | * Base class for regexp based validators.
9 | *
10 | * @see DomainValidator
11 | *
12 | * @see EmailValidator
13 | *
14 | * @see IpAddressValidator
15 | *
16 | * @see PhoneValidator
17 | *
18 | * @see WebUrlValidator
19 | */
20 | open class PatternValidator(_customErrorMessage: String, private val pattern: Pattern) : TextValidator(_customErrorMessage) {
21 |
22 | constructor(errorMessage: String, regex: String) : this(errorMessage, Pattern.compile(regex))
23 |
24 | override fun isValid(text: String): Boolean {
25 | return pattern.matcher(text).matches()
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/AutoCompleteTextViewActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.View
6 | import android.widget.Toast
7 | import com.sha.formvalidator.widget.FormAutoCompleteTextView
8 | import com.sha.formvalidatorsample.R
9 |
10 | class AutoCompleteTextViewActivity : Activity() {
11 |
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | setContentView(R.layout.activity_auto_complete)
15 | }
16 |
17 | fun onClickValidate(v: View) {
18 | val autoCompleteTv = findViewById(R.id.autoCompleteTv)
19 | if (autoCompleteTv.validate())
20 | Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show()
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/TextViewAttrInfo.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import android.content.Context
4 | import android.text.TextUtils
5 | import com.sha.formvalidator.R
6 |
7 | class TextViewAttrInfo {
8 | var errorMessage: String = ""
9 | var required = true
10 | var validationType: TextViewValidationType? = null
11 | var customValidationType: String = ""
12 |
13 | var regex: String = ""
14 | var dateFormat: String = ""
15 |
16 | var emptyErrorMessage: String = ""
17 |
18 | var minNumber: Int = 0
19 | var maxNumber: Int = 0
20 |
21 | var floatMinNumber: Float = 0f
22 | var floatMaxNumber: Float = 0f
23 |
24 | fun emptyErrorMessage(context: Context): String {
25 | return if (!TextUtils.isEmpty(emptyErrorMessage))
26 | emptyErrorMessage else context.getString(R.string.required)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/RxFormActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.widget.Toast
6 | import com.sha.formvalidatorsample.R
7 | import io.reactivex.disposables.CompositeDisposable
8 | import kotlinx.android.synthetic.main.activity_form.*
9 |
10 | class RxFormActivity : Activity() {
11 | private val compositeDisposable = CompositeDisposable()
12 |
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | setContentView(R.layout.activity_form)
16 |
17 | form.validateOnClick(btnValidateFormLayout) {
18 | Toast.makeText(this, "Form result: $it", Toast.LENGTH_SHORT).show()
19 | }
20 | }
21 |
22 | override fun onDestroy() {
23 | super.onDestroy()
24 | compositeDisposable.dispose()
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/composite/AndValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator.composite
2 |
3 | import com.sha.formvalidator.textview.validator.TextValidator
4 |
5 | /**
6 | * The AND validator checks if all of the passed validators is returning true.
7 | * Note: the message that will be shown is the one of the first failing validator
8 | *
9 | */
10 | class AndValidator(vararg validators: TextValidator) : CompositeValidator("", *validators) {
11 |
12 | override fun isValid(text: String): Boolean {
13 | val anyFails = validators.firstOrNull { !it.isValid(text) }
14 | anyFails?.let {
15 | // error message equals the first failing validator
16 | this.errorMessage = it.errorMessage
17 | return false // Remember :) We're acting like an && operator.
18 | }
19 | // true if no one fails
20 | return true
21 | }
22 | }
23 |
24 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/util/SnackBarUtil.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.util
2 |
3 | import android.os.Handler
4 | import android.view.View
5 | import android.widget.TextView
6 |
7 | import com.google.android.material.snackbar.Snackbar
8 | import com.sha.formvalidatorsample.R
9 |
10 | object SnackBarUtil {
11 |
12 | fun gotIt(view: View, text: String) {
13 | Handler().postDelayed({
14 | multilineSnackbar(
15 | Snackbar.make(
16 | view, text, Snackbar.LENGTH_INDEFINITE)
17 | .setAction("Got it") {
18 |
19 | }
20 | ).show()
21 | }, 200)
22 | }
23 |
24 | private fun multilineSnackbar(snackbar: Snackbar): Snackbar {
25 | val textView = snackbar.view.findViewById(R.id.snackbar_text)
26 | textView.maxLines = 5
27 | return snackbar
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable/rect_border.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
11 |
12 |
15 |
16 |
22 |
23 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
18 |
27 |
28 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/NumericValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | /**
4 | * A validator that returns true only if the input field contains only numbers.
5 | *
6 | */
7 | class NumericValidator(errorMessage: String) : TextValidator(errorMessage) {
8 |
9 | override fun isValid(text: String): Boolean {
10 | return if(text.isEmpty()) false else isDigitsOnly(text)
11 | }
12 |
13 | /**
14 | * This function is copied from [android.text.TextUtils]
15 | * to be able to run unit test with mockito
16 | */
17 | private fun isDigitsOnly(str: CharSequence): Boolean {
18 | val len = str.length
19 | var cp: Int
20 | var i = 0
21 | while (i < len) {
22 | cp = Character.codePointAt(str, i)
23 | if (!Character.isDigit(cp)) {
24 | return false
25 | }
26 | i += Character.charCount(cp)
27 | }
28 | return true
29 | }
30 | }
31 |
32 |
33 |
--------------------------------------------------------------------------------
/fastlane/README.md:
--------------------------------------------------------------------------------
1 | fastlane documentation
2 | ================
3 | # Installation
4 |
5 | Make sure you have the latest version of the Xcode command line tools installed:
6 |
7 | ```
8 | xcode-select --install
9 | ```
10 |
11 | Install _fastlane_ using
12 | ```
13 | [sudo] gem install fastlane -NV
14 | ```
15 | or alternatively using `brew install fastlane`
16 |
17 | # Available Actions
18 | ## Android
19 | ### android test
20 | ```
21 | fastlane android test
22 | ```
23 | Runs all the tests
24 | ### android beta
25 | ```
26 | fastlane android beta
27 | ```
28 | Submit a new Beta Build to Crashlytics Beta
29 | ### android deploy
30 | ```
31 | fastlane android deploy
32 | ```
33 | Deploy a new version to the Google Play
34 |
35 | ----
36 |
37 | This README.md is auto-generated and will be re-generated every time [fastlane](https://fastlane.tools) is run.
38 | More information about fastlane can be found on [fastlane.tools](https://fastlane.tools).
39 | The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools).
40 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/adapter/FieldItem.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.adapter
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 |
7 | import com.sha.formvalidatorsample.presentation.FieldActivity
8 |
9 | class FieldItem {
10 | private lateinit var clazz: Class
11 | var layoutRes = -1
12 | var description: Int = 0
13 | var title: String
14 |
15 | constructor(title: String, _clazz: Class) {
16 | this.title = title
17 | clazz = _clazz
18 | }
19 |
20 | constructor(title: String, layoutRes: Int, description: Int) {
21 | this.title = title
22 | this.layoutRes = layoutRes
23 | this.description = description
24 | }
25 |
26 | fun showDemo(ctx: Context) {
27 | if (layoutRes != -1) {
28 | ctx.startActivity(FieldActivity.buildIntent(ctx, title, layoutRes, description))
29 | return
30 | }
31 | ctx.startActivity(Intent(ctx, clazz))
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/FieldsActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import android.view.MenuItem
6 | import android.view.View
7 |
8 | import androidx.appcompat.app.AppCompatActivity
9 | import androidx.recyclerview.widget.LinearLayoutManager
10 | import androidx.recyclerview.widget.RecyclerView
11 |
12 | import com.sha.formvalidatorsample.R
13 | import com.sha.formvalidatorsample.adapter.RecyclerAdapter
14 | import com.sha.formvalidatorsample.util.SnackBarUtil
15 |
16 |
17 | class FieldsActivity : AppCompatActivity() {
18 |
19 | public override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | setContentView(R.layout.activity_examples)
22 |
23 | setupList()
24 | }
25 |
26 | private fun setupList() {
27 | val rv = findViewById(R.id.rv)
28 | rv.layoutManager = LinearLayoutManager(this)
29 | rv.adapter = RecyclerAdapter()
30 | }
31 |
32 | }
--------------------------------------------------------------------------------
/fastlane/Fastfile:
--------------------------------------------------------------------------------
1 | # This file contains the fastlane.tools configuration
2 | # You can find the documentation at https://docs.fastlane.tools
3 | #
4 | # For a list of all available actions, check out
5 | #
6 | # https://docs.fastlane.tools/actions
7 | #
8 | # For a list of all available plugins, check out
9 | #
10 | # https://docs.fastlane.tools/plugins/available-plugins
11 | #
12 |
13 | # Uncomment the line if you want fastlane to automatically update itself
14 | # update_fastlane
15 |
16 | default_platform(:android)
17 |
18 | platform :android do
19 | desc "Runs all the tests"
20 | lane :test do
21 | gradle(task: "assembleDebug")
22 | end
23 |
24 | desc "Submit a new Beta Build to Crashlytics Beta"
25 | lane :beta do
26 | gradle(task: "clean assembleRelease")
27 | crashlytics
28 |
29 | # sh "your_script.sh"
30 | # You can also use other beta testing services here
31 | end
32 |
33 | desc "Deploy a new version to the Google Play"
34 | lane :deploy do
35 | gradle(task: "clean assembleRelease")
36 | upload_to_play_store
37 | end
38 | end
39 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/TextValidationHandler.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import android.content.Context
4 |
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 |
7 | /**
8 | * Interface for encapsulating validation of an EditText control
9 | */
10 | interface TextValidationHandler {
11 |
12 | val isRequired: Boolean
13 | /**
14 | * Add a validator to this FormEditText. The validator will be added in the
15 | * queue of the current validators.
16 | *
17 | * @param validator
18 | */
19 | fun addValidator(validator: TextValidator)
20 |
21 | /**
22 | * setup the [TextValidator]s
23 | */
24 | fun setupValidator(context: Context)
25 |
26 | /**
27 | * Calling *validate()* will cause the EditText to go through
28 | * customValidators and call [.Validator.isValid]
29 | *
30 | * @param showError determines if this call should show the UI error.
31 | * @return true if the validity passes false otherwise.
32 | */
33 | fun validate(showError: Boolean = true): Boolean
34 |
35 | fun showError()
36 |
37 | fun hideError()
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/CompositeValidatorInfo.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model
2 |
3 | import android.widget.TextView
4 | import com.sha.formvalidator.textview.ValidatorFactory
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 |
7 | data class CompositeValidatorInfo(
8 | internal var validators: MutableList = mutableListOf()
9 | ) {
10 |
11 | fun validator(vararg validators: TextValidator) {
12 | this.validators.addAll(validators)
13 | }
14 |
15 | fun allValid(vararg validators: TextValidator) {
16 | this.validators.add(ValidatorFactory.allValid(*validators))
17 | }
18 |
19 | fun anyValid(errorMessage: String, vararg validators: TextValidator) {
20 | this.validators.add(ValidatorFactory.anyValid(errorMessage, *validators))
21 | }
22 |
23 | fun valueMatch(errorMessage: String, vararg fields: TextView) {
24 | this.validators.add(ValidatorFactory.valueMatch(errorMessage, *fields))
25 | }
26 |
27 | fun passwordMatch(errorMessage: String, field1: TextView, field2: TextView) {
28 | this.validators.add(ValidatorFactory.passwordMatch(errorMessage, field1, field2))
29 | }
30 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/AndValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.CreditCardValidator
4 | import com.sha.formvalidator.textview.validator.PrefixValidator
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 | import com.sha.formvalidator.textview.validator.composite.AndValidator
7 | import org.junit.Before
8 | import org.junit.Test
9 |
10 | class AndValidatorTest {
11 | lateinit var validator: TextValidator
12 |
13 | @Before
14 | fun setup() {
15 | validator = AndValidator(
16 | CreditCardValidator("Invalid Card!"),
17 | PrefixValidator("3787", "Invalid Prefix!"))
18 | }
19 |
20 | @Test
21 | fun validate_valid() {
22 | assert(validator.isValid("378734493671000"))
23 | }
24 |
25 | @Test
26 | fun validate_firstInvalid() {
27 | assert(!validator.isValid("37873449367100099"))
28 | assert(validator.errorMessage == "Invalid Card!")
29 | }
30 |
31 | @Test
32 | fun validate_secondInvalid() {
33 | assert(!validator.isValid("6331101999990016"))
34 | assert(validator.errorMessage == "Invalid Prefix!")
35 | }
36 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/FormActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.widget.Toast
6 | import com.sha.formvalidator.model.FormOptions
7 | import com.sha.formvalidator.model.IgnoreField
8 | import com.sha.formvalidatorsample.R
9 | import kotlinx.android.synthetic.main.activity_form.*
10 |
11 | class FormActivity : Activity() {
12 | override fun onCreate(savedInstanceState: Bundle?) {
13 | super.onCreate(savedInstanceState)
14 | setContentView(R.layout.activity_form)
15 | form.validateOnClick(btnValidateFormLayout) {
16 | Toast.makeText(this, "Form result: $it", Toast.LENGTH_SHORT).show()
17 | }
18 | setupForm()
19 | }
20 |
21 | private fun setupForm() {
22 | form.options = FormOptions.create {
23 | validationInterceptor = { field ->
24 | when(field.id) {
25 | R.id.etIgnored -> IgnoreField.YES
26 | else -> IgnoreField.NO
27 | }
28 | }
29 | ignoreFieldsIds = listOf(R.id.etIgnoredId)
30 | ignoreHiddenFields = true
31 | shakeOnError = true
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/adapter/RecyclerAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.adapter
2 |
3 | import android.view.LayoutInflater
4 | import android.view.View
5 | import android.view.ViewGroup
6 | import android.widget.TextView
7 | import androidx.recyclerview.widget.RecyclerView
8 |
9 | import com.sha.formvalidatorsample.R
10 |
11 | class RecyclerAdapter : RecyclerView.Adapter() {
12 |
13 | inner class Vh(itemView: View) : RecyclerView.ViewHolder(itemView) {
14 | private val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
15 |
16 | init {
17 | itemView.setOnClickListener { items[adapterPosition].showDemo(itemView.context) }
18 | }
19 |
20 | fun onBind(item: FieldItem) {
21 | tvTitle.text = item.title
22 | }
23 | }
24 |
25 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Vh {
26 | return Vh(LayoutInflater.from(parent.context)
27 | .inflate(R.layout.item_example, parent, false))
28 | }
29 |
30 | override fun onBindViewHolder(holder: Vh, position: Int) = holder.onBind(items[position])
31 |
32 | override fun getItemCount() = items.size
33 |
34 | companion object {
35 | private val items = FieldInfo.items
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/core/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Only numeric digits are allowed.
4 | Only numeric digits within the range %1$s - %2$s are allowed.
5 | This field cannot contain any special character
6 | Only standard letters are allowed
7 | Required
8 | Email address not valid
9 | Credit card number is not valid
10 | Phone number not valid
11 | Domain name not valid
12 | IP Address not valid
13 | Web Url is not valid
14 | Not a valid first or last name.
15 | Not a valid full name.
16 | Format not valid
17 |
--------------------------------------------------------------------------------
/rxjava/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Only numeric digits are allowed.
4 | Only numeric digits within the range %1$s - %2$s are allowed.
5 | This field cannot contain any special character
6 | Only standard letters are allowed
7 | Required
8 | Email address not valid
9 | Credit card number is not valid
10 | Phone number not valid
11 | Domain name not valid
12 | IP Address not valid
13 | Web Url is not valid
14 | Not a valid first or last name.
15 | Not a valid full name.
16 | Format not valid
17 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_auto_complete.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
14 |
17 |
18 |
25 |
26 |
29 |
30 |
36 |
37 |
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
11 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/validator/OrValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.validator
2 |
3 | import com.sha.formvalidator.textview.validator.CreditCardValidator
4 | import com.sha.formvalidator.textview.validator.PrefixValidator
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 | import com.sha.formvalidator.textview.validator.composite.OrValidator
7 | import org.junit.Before
8 | import org.junit.Test
9 |
10 | class OrValidatorTest {
11 | lateinit var validator: TextValidator
12 |
13 | @Before
14 | fun setup() {
15 | validator = OrValidator(
16 | "Invalid!",
17 | CreditCardValidator("Invalid Card!"),
18 | PrefixValidator("3787", "Invalid Prefix!"))
19 | }
20 |
21 | @Test
22 | fun validate_valid() {
23 | assert(validator.isValid("378734493671000"))
24 | }
25 |
26 | @Test
27 | fun validate_firstInvalid() {
28 | assert(validator.isValid("37873449367100099"))
29 | assert(validator.errorMessage == "Invalid!")
30 | }
31 |
32 | @Test
33 | fun validate_secondInvalid() {
34 | assert(validator.isValid("6331101999990016"))
35 | assert(validator.errorMessage == "Invalid!")
36 | }
37 |
38 | @Test
39 | fun validate_allInvalid() {
40 | assert(!validator.isValid("63311019999900168"))
41 | assert(validator.errorMessage == "Invalid!")
42 | }
43 | }
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/FormValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import org.junit.Test
4 |
5 | class FormValidatorTest {
6 |
7 | @Test
8 | fun isValid_allValid() {
9 | val validator = FormValidator(
10 | FakeValidValidator(),
11 | FakeValidValidator(),
12 | FakeValidValidator())
13 | assert(validator.isValid)
14 | }
15 |
16 | @Test
17 | fun isValid_someInValid() {
18 | val validator = FormValidator(
19 | FakeValidValidator(),
20 | FakeInvalidValidator(),
21 | FakeInvalidValidator(),
22 | FakeValidValidator())
23 | assert(!validator.isValid)
24 | }
25 |
26 | @Test
27 | fun isValid_allInValid() {
28 | val validator = FormValidator(
29 | FakeInvalidValidator(),
30 | FakeInvalidValidator(),
31 | FakeInvalidValidator(),
32 | FakeInvalidValidator())
33 | assert(!validator.isValid)
34 | }
35 |
36 | @Test
37 | fun isValid_empty() {
38 | val validator = FormValidator()
39 | assert(!validator.isValid)
40 | }
41 |
42 | }
43 |
44 | class FakeValidValidator: Validatable {
45 | override fun validate(): Boolean = true
46 | }
47 |
48 | class FakeInvalidValidator: Validatable {
49 | override fun validate(): Boolean = false
50 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/AbstractFormValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import android.view.View
4 | import com.sha.formvalidator.model.FormOptions
5 | import com.sha.formvalidator.model.helper.AnimationHelper
6 |
7 | /**
8 | * The base form validator that all validators must extend.
9 | */
10 | open class AbstractFormValidator {
11 | private var options: FormOptions = FormOptions.defaultOptions()
12 | private var fields: List = emptyList()
13 | val isValid: Boolean
14 | get() {
15 | if(fields.isEmpty()) return false
16 | var isValid = true
17 | fields.forEach {
18 | val fieldValid = it.validate()
19 | isValid = fieldValid && isValid
20 | if(options.shakeOnError && !fieldValid) AnimationHelper.error(it as View)
21 | }
22 | return isValid
23 | }
24 | /**
25 | * create an instance with list of fields to be validated.
26 | */
27 | constructor(options: FormOptions, fields: List) {
28 | this.fields = fields
29 | this.options = options
30 | }
31 |
32 | /**
33 | * create an instance with var args of fields to be
34 | * validated.
35 | */
36 | @SafeVarargs
37 | constructor(options: FormOptions, vararg fields: T) {
38 | this.fields = fields.asList()
39 | this.options = options
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/model/FormOptions.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.model
2 |
3 | import android.view.View
4 |
5 | enum class IgnoreField { YES, NO }
6 |
7 | data class FormOptions(
8 | var validationInterceptor: ((View) -> IgnoreField)? = null,
9 | var ignoreFieldsIds: List = emptyList(),
10 | var ignoreHiddenFields: Boolean = true,
11 | var shakeOnError: Boolean = true
12 | ){
13 |
14 | class Builder {
15 | private val options = FormOptions()
16 |
17 | fun validationInterceptor(interceptor: (((View) -> IgnoreField)?)): Builder {
18 | options.validationInterceptor = interceptor
19 | return this
20 | }
21 |
22 | fun ignoreFieldsIds(ids: List): Builder {
23 | options.ignoreFieldsIds = ids
24 | return this
25 | }
26 |
27 | fun ignoreHiddenFields(ignore: Boolean): Builder {
28 | options.ignoreHiddenFields = ignore
29 | return this
30 | }
31 |
32 | fun shakeOnError(shake: Boolean): Builder {
33 | options.shakeOnError = shake
34 | return this
35 | }
36 |
37 | fun build(): FormOptions {
38 | return options
39 | }
40 | }
41 |
42 | companion object {
43 | fun defaultOptions(): FormOptions = Builder().build()
44 | fun create(block: FormOptions.() -> Unit) = FormOptions().apply { block() }
45 | }
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/DateValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 | import android.annotation.SuppressLint
4 | import java.text.DateFormat
5 | import java.text.ParseException
6 | import java.text.SimpleDateFormat
7 | import java.util.*
8 |
9 |
10 | class DateValidator(errorMessage: String, _format: String) : TextValidator(errorMessage) {
11 | private val formats: Array = if (_format.isNotEmpty())
12 | _format.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
13 | else
14 | arrayOf("DefaultDate", "DefaultTime", "DefaultDateTime")
15 |
16 | @SuppressLint("SimpleDateFormat")
17 | override fun isValid(text: String): Boolean {
18 | if (text.isEmpty()) return false
19 |
20 | for (_format in formats) {
21 |
22 | val format: DateFormat = when (_format) {
23 | "DefaultDate" -> SimpleDateFormat.getDateInstance()
24 |
25 | "DefaultTime" -> SimpleDateFormat.getTimeInstance()
26 |
27 | "DefaultDateTime" -> SimpleDateFormat.getDateTimeInstance()
28 |
29 | else -> SimpleDateFormat(_format)
30 | }
31 |
32 | val date: Date?
33 |
34 | try {
35 | date = format.parse(text)
36 | } catch (e: ParseException) {
37 | return false
38 | }
39 |
40 | if (date != null) return true
41 | }
42 |
43 | return false
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/PasswordValidatorActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.View
6 | import android.widget.TextView
7 | import android.widget.Toast
8 |
9 | import com.sha.formvalidator.textview.ValidatorFactory
10 | import com.sha.formvalidator.widget.FormEditText
11 | import com.sha.formvalidatorsample.R
12 |
13 | class PasswordValidatorActivity : Activity() {
14 |
15 | override fun onCreate(savedInstanceState: Bundle?) {
16 | super.onCreate(savedInstanceState)
17 | setContentView(R.layout.activity_password)
18 |
19 | val tvDescription = findViewById(R.id.tv_description)
20 | val tvTitle = findViewById(R.id.tv_title)
21 |
22 | tvDescription.setText(R.string.password_description)
23 | tvTitle.setText(R.string.passwords_match)
24 |
25 | //Interesting stuff starts here
26 |
27 | val etPassword = findViewById(R.id.etPassword)
28 | val etConfirmPassword = findViewById(R.id.etConfirmPassword)
29 |
30 | etPassword.addValidator(ValidatorFactory.passwordMatch(
31 | "Passwords don't match!",
32 | etPassword,
33 | etConfirmPassword
34 | ))
35 | }
36 |
37 | fun onClickValidate(v: View) {
38 | val fdt = findViewById(R.id.etPassword)
39 | if (!fdt.validate()) return
40 | Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show()
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/validator/CreditCardValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview.validator
2 |
3 |
4 | /**
5 | * This validator takes care of validating the edittext. The input will be valid only if the number is a valid credit card.
6 | *
7 | */
8 | class CreditCardValidator(errorMessage: String = "") : TextValidator(errorMessage) {
9 |
10 | override fun isValid(text: String): Boolean {
11 | return try {
12 | validateCardNumber(text)
13 | } catch (e: Exception) {
14 | false
15 | }
16 | }
17 |
18 | companion object {
19 | /**
20 | * Validates the credit card number using the Luhn algorithm
21 | *
22 | * @param cardNumber the credit card number
23 | * @return
24 | */
25 | @Throws(NumberFormatException::class)
26 | fun validateCardNumber(cardNumber: String): Boolean {
27 | var sum = 0
28 | var digit: Int
29 | var addend: Int
30 | var doubled = false
31 | for (i in cardNumber.length - 1 downTo 0) {
32 | digit = Integer.parseInt(cardNumber.substring(i, i + 1))
33 | if (doubled) {
34 | addend = digit * 2
35 | if (addend > 9) {
36 | addend -= 9
37 | }
38 | } else {
39 | addend = digit
40 | }
41 | sum += addend
42 | doubled = !doubled
43 | }
44 | return sum % 10 == 0
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/FormOptionsTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import com.sha.formvalidator.model.FormOptions
4 | import com.sha.formvalidator.model.IgnoreField
5 | import org.junit.Test
6 |
7 | class FormOptionsTest {
8 |
9 | @Test
10 | fun dsl_validationInterceptor() {
11 | val options = FormOptions.create { validationInterceptor = { IgnoreField.YES } }
12 | assert(options.validationInterceptor != null)
13 | }
14 |
15 | @Test
16 | fun dsl_ignoreFieldsIds() {
17 | val options = FormOptions.create { ignoreFieldsIds = listOf(1, 2) }
18 | assert(options.ignoreFieldsIds.size == 2)
19 | }
20 |
21 | @Test
22 | fun dsl_ignoreHiddenFields() {
23 | val options = FormOptions.create { ignoreHiddenFields = false }
24 | assert(!options.ignoreHiddenFields)
25 | }
26 |
27 | @Test
28 | fun builder_validationInterceptor() {
29 | val options = FormOptions.Builder()
30 | .validationInterceptor { IgnoreField.YES }
31 | .build()
32 | assert(options.validationInterceptor != null)
33 | }
34 |
35 | @Test
36 | fun builder_ignoreFieldsIds() {
37 | val options = FormOptions.Builder()
38 | .ignoreFieldsIds(listOf(1, 2))
39 | .build()
40 | assert(options.ignoreFieldsIds.size == 2)
41 | }
42 |
43 | @Test
44 | fun builder_ignoreHiddenFields() {
45 | val options = FormOptions.Builder()
46 | .ignoreHiddenFields(false)
47 | .build()
48 | assert(!options.ignoreHiddenFields)
49 | }
50 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/FormValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import android.view.View
4 | import com.sha.formvalidator.model.FormOptions
5 |
6 | /**
7 | * The class responsible for validating fields
8 | */
9 | class FormValidator : AbstractFormValidator {
10 |
11 | /**
12 | * create an instance with list of fields to be validated.
13 | * @param fields the fields to be validated.
14 | */
15 | constructor(options: FormOptions = FormOptions.defaultOptions(), fields: List) : super(options, fields)
16 |
17 | /**
18 | * create an instance with list of fields to be validated.
19 | * @param fields the fields to be validated.
20 | */
21 | constructor(fields: List) : super(FormOptions.defaultOptions(), fields)
22 |
23 | /**
24 | * create an instance with var args of fields to be
25 | * validated.
26 | * @param fields the fields to be validated.
27 | */
28 | @SafeVarargs
29 | constructor(options: FormOptions = FormOptions.defaultOptions(), vararg fields: T) : super(options, *fields)
30 |
31 | /**
32 | * create an instance with var args of fields to be
33 | * validated.
34 | * @param fields the fields to be validated.
35 | */
36 | constructor(vararg fields: T) : super(FormOptions.defaultOptions(), *fields)
37 |
38 | /**
39 | * Set a listener to the view to validate on click
40 | * @param view the view that triggers validation
41 | */
42 | fun validateOnClick(view: View, listener: (Boolean) -> Unit) {
43 | view.setOnClickListener { listener(isValid) }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/common.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: Plugins.kotlinAndroid
2 | apply plugin: Plugins.kotlinAndroidExtensions
3 | apply plugin: Plugins.kotlinKapt
4 |
5 | android {
6 | compileSdkVersion Config.compileSdk
7 |
8 | defaultConfig {
9 | minSdkVersion Config.minSdk
10 | targetSdkVersion Config.targetSdk
11 | versionCode Config.versionCode
12 | versionName Config.versionName
13 | vectorDrawables.useSupportLibrary = true
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles 'consumer-rules.pro'
17 | multiDexEnabled true
18 |
19 | }
20 |
21 | android {
22 | lintOptions { abortOnError false }
23 | testOptions { unitTests.includeAndroidResources = true }
24 | }
25 |
26 | compileOptions {
27 | targetCompatibility Config.javaVersion
28 | sourceCompatibility Config.javaVersion
29 | }
30 |
31 | packagingOptions {
32 | exclude 'META-INF/rxjava.properties'
33 | exclude 'META-INF/DEPENDENCIES.txt'
34 | exclude 'META-INF/LICENSE.txt'
35 | exclude 'META-INF/NOTICE.txt'
36 | exclude 'META-INF/NOTICE'
37 | exclude 'META-INF/LICENSE'
38 | exclude 'META-INF/DEPENDENCIES'
39 | exclude 'META-INF/notice.txt'
40 | exclude 'META-INF/license.txt'
41 | exclude 'META-INF/dependencies.txt'
42 | exclude 'META-INF/LGPL2.1'
43 | exclude 'META-INF/MANIFEST.MF'
44 | }
45 | }
46 |
47 | dependencies {
48 | implementation fileTree(dir: 'libs', include: ['*.jar'])
49 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
50 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/Form.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.view.View
6 | import android.widget.LinearLayout
7 | import com.sha.formvalidator.model.FormOptions
8 |
9 | /**
10 | * A [LinearLayout] that wraps all [Validatable] fields and applies
11 | * different validators on each field.
12 | */
13 | open class Form: LinearLayout {
14 |
15 | open lateinit var formHelper: FormHelper
16 |
17 | var options: FormOptions = FormOptions.defaultOptions()
18 |
19 | constructor(context: Context) : super(context) { setup(null) }
20 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
21 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
22 | setup(attrs)
23 | }
24 |
25 | private fun setup(attrs: AttributeSet?) {
26 | formHelper = FormHelper()
27 |
28 | // the view is added programmatically
29 | if (attrs == null) return
30 |
31 | context.obtainStyledAttributes(attrs, R.styleable.Form).run {
32 | options.shakeOnError = getBoolean(R.styleable.Form_shakeOnError, true)
33 | options.ignoreHiddenFields = getBoolean(R.styleable.Form_ignoreHiddenFields, true)
34 | recycle()
35 | }
36 | }
37 |
38 | open fun validate(): Boolean = FormValidator(options, formHelper.fields(this, options)).isValid
39 |
40 | open fun validateOnClick(view: View, validationCallback: (Boolean) -> Unit) {
41 | view.setOnClickListener { validationCallback(validate()) }
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_field.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
15 |
16 |
19 |
20 |
27 |
28 |
31 |
32 |
36 |
37 |
40 |
41 |
48 |
49 |
--------------------------------------------------------------------------------
/core/src/test/java/com/sha/formvalidator/RxFormValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import org.junit.Test
4 |
5 | class RxFormValidatorTest {
6 |
7 | @Test
8 | fun isValid_allValid() {
9 | val validator = RxFormValidator(
10 | FakeValidValidator(),
11 | FakeValidValidator(),
12 | FakeValidValidator())
13 | validator.validate()
14 | .test()
15 | .assertNoErrors()
16 | .assertValue(true)
17 | .assertValueCount(1)
18 | }
19 |
20 | @Test
21 | fun isValid_someInValid() {
22 | val validator = RxFormValidator(
23 | FakeValidValidator(),
24 | FakeInvalidValidator(),
25 | FakeInvalidValidator(),
26 | FakeValidValidator())
27 | validator.validate()
28 | .test()
29 | .assertNoErrors()
30 | .assertValue(false)
31 | .assertValueCount(1)
32 | }
33 |
34 | @Test
35 | fun isValid_allInValid() {
36 | val validator = RxFormValidator(
37 | FakeInvalidValidator(),
38 | FakeInvalidValidator(),
39 | FakeInvalidValidator(),
40 | FakeInvalidValidator())
41 | validator.validate()
42 | .test()
43 | .assertNoErrors()
44 | .assertValue(false)
45 | .assertValueCount(1)
46 | }
47 |
48 | @Test
49 | fun isValid_empty() {
50 | val validator = RxFormValidator()
51 | validator.validate()
52 | .test()
53 | .assertNoErrors()
54 | .assertValue(false)
55 | .assertValueCount(1)
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/FormHelper.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator
2 |
3 | import android.view.View
4 | import android.view.ViewGroup
5 | import com.sha.formvalidator.model.FormOptions
6 | import com.sha.formvalidator.model.IgnoreField
7 |
8 | /**
9 | * Helps collecting all the fields that implement [Validatable] interface
10 | * and applies options.
11 | */
12 | open class FormHelper {
13 |
14 | /**
15 | * Collects fields that implement [Validatable] interface
16 | * and applies options.
17 | * The function is invoked recursively for each [ViewGroup] to collect all
18 | * fields.
19 | * @param viewGroup The view group to collect values from
20 | */
21 | fun fields(viewGroup: ViewGroup, options: FormOptions): List {
22 | val children: MutableList = mutableListOf()
23 |
24 | for (i in 0 until viewGroup.childCount) {
25 | val child = viewGroup.getChildAt(i)
26 |
27 | // the view group may be Validatable, if it's the case, we shouldn't
28 | // loop over its children
29 | if(child !is Validatable && child is ViewGroup) {
30 | // loop recursively to get all children
31 | children += fields(child, options)
32 | continue
33 | }
34 |
35 | // add only Validatable
36 | if (child !is Validatable) continue
37 |
38 | // don't validate hidden fields, if it's desired by client
39 | if (options.ignoreHiddenFields && child.visibility != View.VISIBLE) continue
40 |
41 | // ignore ID
42 | if(options.ignoreFieldsIds.any { it == child.id }) continue
43 |
44 | // apply interceptor
45 | if(options.validationInterceptor?.invoke(child) == IgnoreField.YES) continue
46 |
47 | children += child
48 | }
49 |
50 | return children
51 | }
52 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormToggleButton.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.util.AttributeSet
6 | import androidx.appcompat.widget.AppCompatToggleButton
7 | import com.sha.formvalidator.R
8 | import com.sha.formvalidator.Validatable
9 | import com.sha.formvalidator.model.OnOffValidation
10 |
11 | /**
12 | * An implementation of [Validatable] for [AppCompatToggleButton]
13 | */
14 | open class FormToggleButton: AppCompatToggleButton, Validatable {
15 | private var validation: OnOffValidation = OnOffValidation.ON
16 | private var originalColor: Int = -1
17 |
18 | constructor(context: Context) : super(context) { setup(null) }
19 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
20 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
21 | setup(attrs)
22 | }
23 |
24 | private fun setup(attrs: AttributeSet?) {
25 | originalColor = currentTextColor
26 |
27 | // the view is added programmatically
28 | if (attrs == null) return
29 |
30 | context.obtainStyledAttributes(attrs, R.styleable.FormToggleButton).run {
31 | val attr = getInt(R.styleable.FormToggleButton_toggleButtonValidation, OnOffValidation.ON.value)
32 | recycle()
33 | validation = OnOffValidation.fromValue(attr)
34 | }
35 | }
36 |
37 | override fun validate(): Boolean {
38 | return when(validation) {
39 | OnOffValidation.ON -> {
40 | setTextColor(if(isChecked) originalColor else Color.RED)
41 | isChecked
42 | }
43 |
44 | OnOffValidation.OFF -> {
45 | setTextColor(if(isChecked) Color.RED else originalColor)
46 | !isChecked
47 | }
48 | }
49 | }
50 |
51 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormCheckBox.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.util.AttributeSet
6 | import androidx.appcompat.widget.AppCompatCheckBox
7 | import com.sha.formvalidator.R
8 | import com.sha.formvalidator.Validatable
9 | import com.sha.formvalidator.model.CheckedValidation
10 |
11 | /**
12 | * An implementation of [Validatable] for [AppCompatCheckBox].
13 | */
14 | open class FormCheckBox: AppCompatCheckBox, Validatable {
15 | private var validation: CheckedValidation = CheckedValidation.CHECKED
16 | private var originalColor: Int = -1
17 |
18 | constructor(context: Context) : super(context) { setup(null) }
19 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
20 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
21 | setup(attrs)
22 | }
23 |
24 | private fun setup(attrs: AttributeSet?) {
25 | originalColor = currentTextColor
26 |
27 | // the view is added programmatically
28 | if (attrs == null) return
29 |
30 | context.obtainStyledAttributes(attrs, R.styleable.FormCheckBox).run {
31 | val attr = getInt(R.styleable.FormCheckBox_checkBoxValidation, CheckedValidation.CHECKED.value)
32 | recycle()
33 | validation = CheckedValidation.fromValue(attr)
34 | }
35 | }
36 |
37 | override fun validate(): Boolean {
38 | return when(validation) {
39 | CheckedValidation.CHECKED -> {
40 | setTextColor(if(isChecked) originalColor else Color.RED)
41 | isChecked
42 | }
43 |
44 | CheckedValidation.UNCHECKED -> {
45 | setTextColor(if(isChecked) Color.RED else originalColor)
46 | !isChecked
47 | }
48 | }
49 | }
50 |
51 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/EmailOrCreditCardActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.widget.FrameLayout
8 | import android.widget.TextView
9 | import android.widget.Toast
10 |
11 | import com.sha.formvalidator.textview.ValidatorFactory
12 | import com.sha.formvalidator.textview.validator.CreditCardValidator
13 | import com.sha.formvalidator.textview.validator.pattern.EmailValidator
14 | import com.sha.formvalidator.widget.FormEditText
15 | import com.sha.formvalidatorsample.R
16 |
17 | class EmailOrCreditCardActivity : Activity() {
18 |
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | setContentView(R.layout.activity_field)
22 |
23 | val flContainer = findViewById(R.id.fl)
24 | val tvDescription = findViewById(R.id.tv_description)
25 | val tvTitle = findViewById(R.id.tv_title)
26 |
27 | flContainer.addView(LayoutInflater.from(this).inflate(R.layout.field_email_or_creditcard, flContainer, false))
28 | tvDescription.setText(R.string.description_email_or_credit)
29 | tvTitle.setText(R.string.email_or_credit_title)
30 |
31 | //Interesting stuff starts here
32 |
33 | val fdt = findViewById(R.id.et)
34 |
35 | fdt.addValidator(
36 | ValidatorFactory.anyValid(
37 | "This is neither a creditcard or an email",
38 | CreditCardValidator(),
39 | EmailValidator()
40 | )
41 | )
42 | }
43 |
44 | fun onClickValidate(v: View) {
45 | val fdt = findViewById(R.id.et)
46 | if (fdt.validate()) {
47 | Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show()
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/rxjava/src/main/java/com/sha/formvalidator/rxjava/RxFormValidator.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.rxjava
2 |
3 | import android.view.View
4 | import com.sha.formvalidator.AbstractFormValidator
5 | import com.sha.formvalidator.Validatable
6 | import com.sha.formvalidator.model.FormOptions
7 |
8 | import io.reactivex.Flowable
9 | import io.reactivex.Single
10 | import io.reactivex.processors.PublishProcessor
11 |
12 | /**
13 | * The class responsible for validating fields.
14 | */
15 | class RxFormValidator : AbstractFormValidator {
16 |
17 | /**
18 | * create an instance with list of fields to be validated.
19 | * @param fields the fields to be validated.
20 | */
21 | constructor(options: FormOptions = FormOptions.defaultOptions(), fields: List) : super(options, fields)
22 |
23 | /**
24 | * create an instance with list of fields to be validated.
25 | * @param fields the fields to be validated.
26 | */
27 | constructor(fields: List) : super(FormOptions.defaultOptions(), fields)
28 |
29 | /**
30 | * create an instance with var args of fields to be
31 | * validated.
32 | * @param fields the fields to be validated.
33 | */
34 | @SafeVarargs
35 | constructor(options: FormOptions = FormOptions.defaultOptions(), vararg fields: T) : super(options, *fields)
36 |
37 | /**
38 | * create an instance with var args of fields to be
39 | * validated.
40 | * @param fields the fields to be validated.
41 | */
42 | constructor(vararg fields: T) : super(FormOptions.defaultOptions(), *fields)
43 |
44 | fun validate() = Single.just(isValid)
45 |
46 | /**
47 | * Set a listener to the view to validate on click.
48 | * @param view the view that triggers validation
49 | */
50 | fun validateOnClick(view: View): Flowable {
51 | val pp = PublishProcessor.create()
52 | view.setOnClickListener { pp.onNext(isValid) }
53 | return pp
54 | }
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/ValidatorFactory.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import android.widget.EditText
4 | import android.widget.TextView
5 | import com.sha.formvalidator.textview.validator.TextValidator
6 | import com.sha.formvalidator.textview.validator.ValueMatchValidator
7 | import com.sha.formvalidator.textview.validator.composite.AndValidator
8 | import com.sha.formvalidator.textview.validator.composite.OrValidator
9 |
10 | /**
11 | * Factory for creating composite validators
12 | */
13 | object ValidatorFactory {
14 |
15 | /**
16 | * all validators must be valid.
17 | * @param validators objects
18 | * @return a [TextValidator]
19 | */
20 | fun allValid(vararg validators: TextValidator): TextValidator {
21 | return AndValidator(*validators)
22 | }
23 |
24 | /**
25 | * one validator MUST be valid.
26 | * @param errorMessage string
27 | * @param validators objects
28 | * @return a [TextValidator]
29 | */
30 | fun anyValid(errorMessage: String, vararg validators: TextValidator): TextValidator {
31 | return OrValidator(errorMessage, *validators)
32 | }
33 |
34 | /**
35 | * the value of each [EditText] must be the same.
36 | * @param errorMessage string
37 | * @param fields [TextView]s to be validated
38 | * @return a [TextValidator]
39 | */
40 | fun valueMatch(errorMessage: String, vararg fields: TextView): TextValidator {
41 | val list = Array(fields.size) { fields[it].text.toString() }
42 | return ValueMatchValidator(errorMessage, *list)
43 | }
44 |
45 | /**
46 | * both of password EditTexts must match
47 | * see [.valueMatch]
48 | * @param errorMessage string
49 | * @param field1 object
50 | * @param field2 object
51 | * @return a [TextValidator]
52 | */
53 | fun passwordMatch(errorMessage: String, field1: TextView, field2: TextView): TextValidator {
54 | return ValueMatchValidator(
55 | errorMessage,
56 | field1.text.toString(),
57 | field2.text.toString())
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
20 |
21 |
26 |
27 |
34 |
35 |
40 |
41 |
45 |
46 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormSwitch.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.util.AttributeSet
6 | import androidx.appcompat.widget.SwitchCompat
7 | import com.sha.formvalidator.R
8 | import com.sha.formvalidator.Validatable
9 | import com.sha.formvalidator.model.OnOffValidation
10 |
11 | /**
12 | * An implementation of [Validatable] for [SwitchCompat]
13 | */
14 | open class FormSwitch: SwitchCompat, Validatable {
15 | private var validation: OnOffValidation = OnOffValidation.ON
16 | private var originalColor: Int = -1
17 |
18 | constructor(context: Context) : super(context) { setup(null) }
19 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
20 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
21 | setup(attrs)
22 | }
23 |
24 | private fun setup(attrs: AttributeSet?) {
25 | originalColor = currentTextColor
26 |
27 | // the view is added programmatically
28 | if (attrs == null) return
29 |
30 | context.obtainStyledAttributes(attrs, R.styleable.FormSwitch).run {
31 | val attr = getInt(R.styleable.FormSwitch_switchValidation, OnOffValidation.ON.value)
32 | recycle()
33 | validation = OnOffValidation.fromValue(attr)
34 | }
35 | val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FormSwitch)
36 | validation = OnOffValidation.fromValue(typedArray.getInt(
37 | R.styleable.FormSwitch_switchValidation,
38 | OnOffValidation.ON.value))
39 | typedArray.recycle()
40 | }
41 |
42 | override fun validate(): Boolean {
43 | return when(validation) {
44 | OnOffValidation.ON -> {
45 | setTextColor(if(isChecked) originalColor else Color.RED)
46 | isChecked
47 | }
48 |
49 | OnOffValidation.OFF -> {
50 | setTextColor(if(isChecked) Color.RED else originalColor)
51 | !isChecked
52 | }
53 | }
54 | }
55 |
56 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormSeekBar.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.graphics.drawable.ColorDrawable
6 | import android.util.AttributeSet
7 | import androidx.appcompat.widget.AppCompatSeekBar
8 | import androidx.core.content.ContextCompat
9 | import com.sha.formvalidator.R
10 | import com.sha.formvalidator.Validatable
11 | import com.sha.formvalidator.model.RequiredValidation
12 |
13 | /**
14 | * An implementation of [Validatable] for [AppCompatSeekBar].
15 | */
16 | open class FormSeekBar: AppCompatSeekBar, Validatable {
17 | private var validation: RequiredValidation = RequiredValidation.REQUIRED
18 | private var originalColor: Int = -1
19 |
20 | constructor(context: Context) : super(context) { setup(null) }
21 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
22 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
23 | setup(attrs)
24 | }
25 |
26 | private fun setup(attrs: AttributeSet?) {
27 | originalColor = (background as? ColorDrawable)?.color ?: Color.TRANSPARENT
28 |
29 | // the view is added programmatically
30 | if (attrs == null) return
31 |
32 | context.obtainStyledAttributes(attrs, R.styleable.FormSeekBar).run {
33 | val attr = getInt(R.styleable.FormSeekBar_seekBarValidation,
34 | RequiredValidation.REQUIRED.value)
35 | recycle()
36 | validation = RequiredValidation.fromValue(attr)
37 | }
38 | }
39 |
40 | private fun isValid(): Boolean = progress > 0
41 |
42 | private fun validationColor(isValid: Boolean): Int {
43 | return if(isValid) originalColor else ContextCompat.getColor(context, R.color.red_light)
44 | }
45 |
46 | override fun validate(): Boolean {
47 | return when(validation) {
48 | RequiredValidation.REQUIRED -> {
49 | val isValid = isValid()
50 | setBackgroundColor(validationColor(isValid))
51 | isValid
52 | }
53 |
54 | RequiredValidation.NOT_REQUIRED -> { true }
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_password.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
16 |
17 |
20 |
21 |
28 |
29 |
32 |
33 |
40 |
41 |
44 |
45 |
52 |
53 |
56 |
57 |
64 |
65 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormRatingBar.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.graphics.drawable.ColorDrawable
6 | import android.util.AttributeSet
7 | import androidx.appcompat.widget.AppCompatRatingBar
8 | import androidx.core.content.ContextCompat
9 | import com.sha.formvalidator.R
10 | import com.sha.formvalidator.Validatable
11 | import com.sha.formvalidator.model.RequiredValidation
12 |
13 | /**
14 | * An implementation of [Validatable] for [AppCompatRatingBar].
15 | */
16 | open class FormRatingBar: AppCompatRatingBar, Validatable {
17 | private var validation: RequiredValidation = RequiredValidation.REQUIRED
18 | private var originalColor: Int = -1
19 |
20 | constructor(context: Context) : super(context) { setup(null) }
21 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
22 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
23 | setup(attrs)
24 | }
25 |
26 | private fun setup(attrs: AttributeSet?) {
27 | originalColor = (background as? ColorDrawable)?.color ?: Color.TRANSPARENT
28 |
29 | // the view is added programmatically
30 | if (attrs == null) return
31 |
32 | context.obtainStyledAttributes(attrs, R.styleable.FormRatingBar).run {
33 | val attr = getInt(R.styleable.FormRatingBar_ratingBarValidation,
34 | RequiredValidation.REQUIRED.value)
35 | recycle()
36 | validation = RequiredValidation.fromValue(attr)
37 | }
38 | }
39 |
40 | private fun isValid(): Boolean = rating > 0
41 |
42 | private fun validationColor(isValid: Boolean): Int {
43 | return if(isValid) originalColor else ContextCompat.getColor(context, R.color.red_light)
44 | }
45 |
46 | override fun validate(): Boolean {
47 | return when(validation) {
48 | RequiredValidation.REQUIRED -> {
49 | val isValid = isValid()
50 | setBackgroundColor(validationColor(isValid))
51 | isValid
52 | }
53 |
54 | RequiredValidation.NOT_REQUIRED -> { true }
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/PrefixAndRangeValidatorActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.os.Bundle
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.widget.FrameLayout
8 | import android.widget.TextView
9 | import android.widget.Toast
10 |
11 | import com.sha.formvalidator.textview.ValidatorFactory
12 | import com.sha.formvalidator.textview.validator.PrefixValidator
13 | import com.sha.formvalidator.textview.validator.LengthRangeValidator
14 | import com.sha.formvalidator.widget.FormEditText
15 | import com.sha.formvalidatorsample.R
16 |
17 | class PrefixAndRangeValidatorActivity : Activity() {
18 |
19 | override fun onCreate(savedInstanceState: Bundle?) {
20 | super.onCreate(savedInstanceState)
21 | setContentView(R.layout.activity_field)
22 | setupUi()
23 |
24 | //Interesting stuff starts here
25 | val fdt = findViewById(R.id.et)
26 |
27 | fdt.addValidators {
28 | allValid(
29 | PrefixValidator("d", "Must start with d."),
30 | LengthRangeValidator("Must be of length 1-5.", 1, 5))
31 | }
32 |
33 | // OR add using ValidatorFactory (appropriate for Java)
34 | fdt.addValidator(
35 | ValidatorFactory.allValid(
36 | PrefixValidator("d", "Must start with d."),
37 | LengthRangeValidator("Must be of length 1-5.", 1, 5)))
38 | }
39 |
40 | private fun setupUi() {
41 | val flContainer = findViewById(R.id.fl)
42 | val tvDescription = findViewById(R.id.tv_description)
43 | val tvTitle = findViewById(R.id.tv_title)
44 |
45 | flContainer.addView(LayoutInflater.from(this).inflate(R.layout.field_email_or_creditcard, flContainer, false))
46 | tvDescription.setText(R.string.description_email_or_credit)
47 | tvTitle.setText(R.string.email_or_credit_title)
48 |
49 | }
50 |
51 | fun onClickValidate(v: View) {
52 | val fdt = findViewById(R.id.et)
53 | if (fdt.validate()) {
54 | Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show()
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/FieldActivity.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.content.Intent
6 | import android.os.Bundle
7 | import android.view.LayoutInflater
8 | import android.view.View
9 | import android.widget.FrameLayout
10 | import android.widget.TextView
11 | import android.widget.Toast
12 |
13 | import com.sha.formvalidator.widget.FormEditText
14 | import com.sha.formvalidatorsample.R
15 |
16 | class FieldActivity : Activity() {
17 |
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | setContentView(R.layout.activity_field)
21 |
22 | val fieldRes = intent.getIntExtra(EXTRA_LAYOUT_RES, 0)
23 | val descriptionRes = intent.getIntExtra(EXTRA_LAYOUT_EXPL_STR_RES, 0)
24 | val title = intent.getStringExtra(EXTRA_TITLE)
25 |
26 | val flContainer = findViewById(R.id.fl)
27 | val view = LayoutInflater.from(this).inflate(fieldRes, flContainer, false)
28 | flContainer.addView(view)
29 |
30 | val tvDescription = findViewById(R.id.tv_description)
31 | tvDescription.setText(descriptionRes)
32 |
33 | val tvTitle = findViewById(R.id.tv_title)
34 | tvTitle.text = title
35 | }
36 |
37 |
38 | fun onClickValidate(v: View) {
39 | val fdt = findViewById(R.id.et)
40 | if (!fdt.validate()) return
41 |
42 | Toast.makeText(this, "Valid", Toast.LENGTH_LONG).show()
43 | }
44 |
45 | companion object {
46 | private const val EXTRA_LAYOUT_RES = "EXTRA_LAYOUT_RES"
47 | private const val EXTRA_LAYOUT_EXPL_STR_RES = "EXTRA_LAYOUT_EXPL_STR_RES"
48 | private const val EXTRA_TITLE = "EXTRA_TITLE"
49 |
50 | fun buildIntent(
51 | ctx: Context,
52 | title: String,
53 | layoutRes: Int,
54 | explanationString: Int
55 | ): Intent {
56 | val toRet = Intent(ctx, FieldActivity::class.java)
57 | toRet.putExtra(EXTRA_TITLE, title)
58 | toRet.putExtra(EXTRA_LAYOUT_RES, layoutRes)
59 | toRet.putExtra(EXTRA_LAYOUT_EXPL_STR_RES, explanationString)
60 | return toRet
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/presentation/CountrySpinner.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.presentation
2 |
3 | import android.content.Context
4 | import android.graphics.Color
5 | import android.graphics.drawable.ColorDrawable
6 | import android.util.AttributeSet
7 | import androidx.appcompat.widget.AppCompatSpinner
8 | import androidx.core.content.ContextCompat
9 | import com.sha.formvalidator.Validatable
10 | import com.sha.formvalidator.model.RequiredValidation
11 | import com.sha.formvalidatorsample.R
12 |
13 | /**
14 | * Custom spinner which is valid only if the first item isn't selected.
15 | * To create a custom Form filed, just implement [Validatable] interface
16 | * and put your validation logic inside validate() function
17 | */
18 | class CountrySpinner: AppCompatSpinner, Validatable {
19 | var validation: RequiredValidation = RequiredValidation.REQUIRED
20 | private var originalColor: Int = -1
21 |
22 | constructor(context: Context) : super(context) { setup(null) }
23 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setup(attrs) }
24 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
25 | setup(attrs)
26 | }
27 |
28 | private fun setup(attrs: AttributeSet?) {
29 | originalColor = (background as? ColorDrawable)?.color ?: Color.TRANSPARENT
30 |
31 | // the view is added programmatically
32 | if (attrs == null) return
33 |
34 | context.obtainStyledAttributes(attrs, R.styleable.CountrySpinner).run {
35 | val attr = getInt(R.styleable.CountrySpinner_countrySpinnerValidation, RequiredValidation.REQUIRED.value)
36 | recycle()
37 | validation = RequiredValidation.fromValue(attr)
38 | }
39 | }
40 |
41 | override fun validate(): Boolean {
42 | return when(validation) {
43 | RequiredValidation.REQUIRED -> {
44 | val isValid = isValid()
45 | setBackgroundColor(validationColor(isValid))
46 | isValid
47 | }
48 |
49 | RequiredValidation.NOT_REQUIRED -> { true }
50 | }
51 | }
52 |
53 | private fun isValid(): Boolean = selectedItem != adapter.getItem(0)
54 |
55 | private fun validationColor(isValid: Boolean): Int {
56 | return if(isValid) originalColor else ContextCompat.getColor(context, R.color.red_light)
57 | }
58 | }
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormAutoCompleteTextView.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import androidx.appcompat.widget.AppCompatAutoCompleteTextView
6 | import com.sha.formvalidator.Validatable
7 | import com.sha.formvalidator.model.CompositeValidatorInfo
8 | import com.sha.formvalidator.textview.DefTextValidationHandler
9 | import com.sha.formvalidator.textview.TextValidationHandler
10 | import com.sha.formvalidator.textview.validator.TextValidator
11 |
12 | /**
13 | * An implementation of [Validatable] for [AppCompatAutoCompleteTextView].
14 | */
15 | open class FormAutoCompleteTextView : AppCompatAutoCompleteTextView, Validatable {
16 | lateinit var validationHandler: TextValidationHandler
17 | constructor(context: Context) : super(context) { setupDefaultValidator(null) }
18 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setupDefaultValidator(attrs) }
19 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
20 | setupDefaultValidator(attrs)
21 | }
22 |
23 | private fun setupDefaultValidator(attrs: AttributeSet?) {
24 | if (attrs == null) {
25 | //support dynamic new FormEditText(context)
26 | validationHandler = DefTextValidationHandler(this, context)
27 | return
28 | }
29 | validationHandler = DefTextValidationHandler(this, attrs, context)
30 | }
31 |
32 | /**
33 | * Add a validator to this AutoCompleteTextView. The validator will be added in the
34 | * queue of the current validators.
35 | *
36 | * @param validator object
37 | */
38 | fun addValidator(validator: TextValidator) {
39 | this.validationHandler.addValidator(validator)
40 | }
41 |
42 | fun addValidators(block: CompositeValidatorInfo.() -> Unit) {
43 | CompositeValidatorInfo().apply { block() }
44 | .validators
45 | .map { validationHandler.addValidator(it) }
46 | }
47 |
48 | /**
49 | * Calling *validate()* will cause the AutoCompleteTextView to go through
50 | * customValidators and call [com.sha.formvalidator.textview.validator.TextValidator.isValid]
51 | *
52 | * @return true if the validity passes false otherwise.
53 | */
54 | override fun validate(): Boolean {
55 | return validationHandler.validate()
56 | }
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/widget/FormEditText.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.widget
2 |
3 | import android.content.Context
4 | import android.graphics.drawable.Drawable
5 | import android.util.AttributeSet
6 | import androidx.appcompat.widget.AppCompatEditText
7 | import com.sha.formvalidator.Validatable
8 | import com.sha.formvalidator.model.CompositeValidatorInfo
9 | import com.sha.formvalidator.textview.DefTextValidationHandler
10 | import com.sha.formvalidator.textview.TextValidationHandler
11 | import com.sha.formvalidator.textview.ValidatorFactory
12 | import com.sha.formvalidator.textview.validator.TextValidator
13 |
14 | /**
15 | * An implementation of [Validatable] for [AppCompatEditText].
16 | */
17 | open class FormEditText : AppCompatEditText, Validatable {
18 | lateinit var validationHandler: TextValidationHandler
19 |
20 | constructor(context: Context) : super(context) { setupDefaultValidator(null, context) }
21 | constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setupDefaultValidator(attrs, context) }
22 | constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
23 | setupDefaultValidator(attrs, context)
24 | }
25 |
26 | private fun setupDefaultValidator(attrs: AttributeSet?, context: Context) {
27 | if (attrs == null) {
28 | //support dynamic new FormEditText(context)
29 | validationHandler = DefTextValidationHandler(this, context)
30 | return
31 | }
32 | validationHandler = DefTextValidationHandler(this, attrs, context)
33 | }
34 |
35 | /**
36 | * Add a validator to this FormEditText. The validator will be added in the
37 | * queue of the current validators.
38 | *
39 | * @param validator object
40 | */
41 | fun addValidator(validator: TextValidator) {
42 | this.validationHandler.addValidator(validator)
43 | }
44 |
45 | fun addValidators(block: CompositeValidatorInfo.() -> Unit) {
46 | CompositeValidatorInfo().apply { block() }
47 | .validators
48 | .map { validationHandler.addValidator(it) }
49 | }
50 |
51 | /**
52 | * validate field
53 | *
54 | * @return true if valid.
55 | */
56 | override fun validate(): Boolean {
57 | return validationHandler.validate()
58 | }
59 |
60 | override fun getBackground(): Drawable? {
61 | val background = super.getBackground()
62 | background?.clearColorFilter()
63 | return background
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/core/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
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 |
81 |
--------------------------------------------------------------------------------
/rxjava/src/main/res/values/attrs.xml:
--------------------------------------------------------------------------------
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 |
81 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/sha/formvalidatorsample/adapter/FieldInfo.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidatorsample.adapter
2 |
3 | import com.sha.formvalidatorsample.R
4 | import com.sha.formvalidatorsample.presentation.AutoCompleteTextViewActivity
5 | import com.sha.formvalidatorsample.presentation.EmailOrCreditCardActivity
6 | import com.sha.formvalidatorsample.presentation.PasswordValidatorActivity
7 | import com.sha.formvalidatorsample.presentation.PrefixAndRangeValidatorActivity
8 |
9 | import java.util.Arrays
10 |
11 | internal object FieldInfo {
12 |
13 | var items = listOf(
14 | FieldItem(
15 | "Alpha With TextInputLayout",
16 | R.layout.field_alpha_textinputlayout,
17 | R.string.description_alpha),
18 | FieldItem(
19 | "Alpha",
20 | R.layout.field_alpha,
21 | R.string.description_alpha),
22 | FieldItem(
23 | "Person Name",
24 | R.layout.field_personname,
25 | R.string.description_person_name),
26 | FieldItem(
27 | "Person Full Name",
28 | R.layout.field_personfullname,
29 | R.string.description_person_full_name),
30 | FieldItem(
31 | "Date",
32 | R.layout.field_date,
33 | R.string.description_date),
34 | FieldItem(
35 | "Date Custom Format",
36 | R.layout.field_date_custom,
37 | R.string.description_date_custom),
38 | FieldItem(
39 | "Numeric only",
40 | R.layout.field_numeric,
41 | R.string.description_numeric),
42 | FieldItem(
43 | "Float Numeric Range",
44 | R.layout.field_float_numeric_range,
45 | R.string.float_numeric_range),
46 | FieldItem(
47 | "Email",
48 | R.layout.field_email,
49 | R.string.description_email),
50 | FieldItem(
51 | "Credit Card Number",
52 | R.layout.field_creditcard,
53 | R.string.description_credit_card),
54 | FieldItem(
55 | "Phone",
56 | R.layout.field_phone,
57 | R.string.description_phone),
58 | FieldItem(
59 | "Domain Name",
60 | R.layout.field_domain_name,
61 | R.string.description_domain_name),
62 | FieldItem(
63 | "IP Address",
64 | R.layout.field_ip_address,
65 | R.string.description_ip_address),
66 | FieldItem(
67 | "WEB Url",
68 | R.layout.field_weburl,
69 | R.string.description_web_url),
70 | FieldItem(
71 | "Regex",
72 | R.layout.field_regex,
73 | R.string.description_regex),
74 | FieldItem(
75 | "Custom Messages",
76 | R.layout.field_phone_custommessages,
77 | R.string.description_phone_custom_messages),
78 | FieldItem(
79 | "Allow Empty",
80 | R.layout.field_allowempty,
81 | R.string.description_allow_empty),
82 | FieldItem(
83 | "Custom validation type",
84 | R.layout.field_custom_validation_type,
85 | R.string.custom_validation_type_description),
86 | FieldItem("Email OR CreditCard", EmailOrCreditCardActivity::class.java),
87 | FieldItem("Suffix AND Range", PrefixAndRangeValidatorActivity::class.java),
88 | FieldItem("Password matching", PasswordValidatorActivity::class.java),
89 | FieldItem("AutoComplete TextView", AutoCompleteTextViewActivity::class.java)
90 | )
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/TextViewValidatorFactory.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import android.text.TextUtils
6 | import com.sha.formvalidator.R
7 | import com.sha.formvalidator.textview.validator.*
8 | import com.sha.formvalidator.textview.validator.pattern.*
9 |
10 | object TextViewValidatorFactory {
11 |
12 | fun validator(
13 | attrInfo: TextViewAttrInfo,
14 | context: Context
15 | ): TextValidator {
16 | val validator = when (attrInfo.validationType) {
17 | TextViewValidationType.NOT_DETECTABLE -> {
18 | if (attrInfo.customValidationType.isNotEmpty())
19 | customValidator(attrInfo, context) else
20 | predefinedValidator(attrInfo, context)
21 | }
22 | else -> predefinedValidator(attrInfo, context)
23 | }
24 |
25 | if (!TextUtils.isEmpty(attrInfo.errorMessage)) validator.errorMessage = attrInfo.errorMessage
26 |
27 | // If the xml tells us that this is not a required field, we will add InverseValidator(RequiredValidator()).
28 | return if (attrInfo.required) ValidatorFactory.allValid(
29 | RequiredValidator(attrInfo.emptyErrorMessage(context)),
30 | validator)
31 | else ValidatorFactory.anyValid(
32 | validator.errorMessage,
33 | InverseValidator(RequiredValidator()),
34 | validator)
35 | }
36 |
37 | private fun customValidator(attrInfo: TextViewAttrInfo, context: Context): TextValidator {
38 | val opt = TextViewValidators.customValidators.firstOrNull {
39 | it.customValidationType(context) == attrInfo.customValidationType
40 | }
41 | check(opt != null) { "couldn't find a custom validator for custom validation type: ${attrInfo.customValidationType}" }
42 | return opt
43 | }
44 |
45 | @SuppressLint("StringFormatMatches")
46 | private fun predefinedValidator(attrInfo: TextViewAttrInfo, context: Context): TextValidator {
47 | return when (attrInfo.validationType) {
48 | TextViewValidationType.NOT_EMPTY -> DummyValidator()
49 | TextViewValidationType.ALPHA -> AlphaValidator(context.getString(R.string.error_only_standard_letters_are_allowed))
50 | TextViewValidationType.ALPHA_NUMERIC -> AlphaNumericValidator(context.getString(R.string.error_this_field_cannot_contain_special_character))
51 | TextViewValidationType.NUMERIC -> NumericValidator(context.getString(R.string.error_only_numeric_digits_allowed))
52 | TextViewValidationType.REGEX -> PatternValidator(attrInfo.errorMessage, attrInfo.regex)
53 | TextViewValidationType.CREDIT_CARD -> CreditCardValidator(context.getString(R.string.error_credit_card_number_not_valid))
54 | TextViewValidationType.EMAIL -> EmailValidator(context.getString(R.string.error_email_address_not_valid))
55 | TextViewValidationType.PHONE -> PhoneValidator(context.getString(R.string.error_phone_not_valid))
56 | TextViewValidationType.DOMAIN_NAME -> DomainValidator(context.getString(R.string.error_domain_not_valid))
57 | TextViewValidationType.IP_ADDRESS -> IpAddressValidator(context.getString(R.string.error_ip_not_valid))
58 | TextViewValidationType.WEB_URL -> WebUrlValidator(context.getString(R.string.error_url_not_valid))
59 | TextViewValidationType.PERSON_NAME -> PersonNameValidator(context.getString(R.string.error_not_valid_person_name))
60 | TextViewValidationType.PERSON_FULL_NAME -> PersonFullNameValidator(context.getString(R.string.error_not_valid_person_full_name))
61 | TextViewValidationType.DATE -> DateValidator(context.getString(R.string.error_date_not_valid), attrInfo.dateFormat)
62 |
63 | TextViewValidationType.NUMERIC_RANGE -> NumericRangeValidator(
64 | context.getString(R.string.error_only_numeric_digits_range_allowed, attrInfo.minNumber, attrInfo.maxNumber),
65 | attrInfo.minNumber.toLong(),
66 | attrInfo.maxNumber.toLong())
67 | TextViewValidationType.FLOAT_NUMERIC_RANGE -> FloatNumericRangeValidator(
68 | context.getString(R.string.error_only_numeric_digits_range_allowed, attrInfo.floatMinNumber, attrInfo.floatMaxNumber),
69 | attrInfo.floatMinNumber.toDouble(),
70 | attrInfo.floatMaxNumber.toDouble())
71 | else -> DummyValidator()
72 | }
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/TEXTVIEW.md:
--------------------------------------------------------------------------------
1 | TextView Validation
2 | ===================
3 | `FormEditText` and `FormAutoCompleteTextView` are predefined `TextView` widgets that implement `validatable` interface.
4 |
5 | ## Attributes
6 |
7 | | **Attribute** | **Description** |
8 | | ----------------- | --------------------------------------------------------- |
9 | | **validationType** | see [TextView validationType Values](#textview-validationtype-values)|
10 | | **errorMessage** | message if the field is invalid |
11 | | **requiredErrorMessage** | message if the field is empty |
12 | | **customValidationType** | a string for custom validation (**see usage below**) |
13 |
14 |
15 | #### TextView `validationType` Values
16 |
17 | | **Type** | **Description** | **Required attributes** |
18 | | ---------------------- | ----------------------------- | ----------------------------------------------- |
19 | | **required** | validates required fields | _ |
20 | | **numeric** | validates numeric only | _ |
21 | | **alpha** | validates alpha only | _ |
22 | | **alphaNumeric** | validates alpha numeric | _ |
23 | | **email** | validates email | _ |
24 | | **creditCard** | validates credit card using [Luhn Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm) | _ |
25 | | **phone** | validates phone | _ |
26 | | **domainName** | validates domain name | _ |
27 | | **ipAddress** | validates IP address | _ |
28 | | **webUrl** | validates web URL | _ |
29 | | **personName** | validates person name | _ |
30 | | **personFullName** | validates person full name | _ |
31 | | **regex** | validates a REGEX | - **regex** |
32 | | **numericRange** | validates numeric range | - **minNumber** - **maxNumber** . |
33 | | **floatNumericRange** | validates floating-point ranges | - **floatMinNumber** - **floatMaxNumber**|
34 | | **date** | validates date | - **dateFormat** |
35 |
36 | ## Custom Validators
37 | There are 2 approaches to create a cutom validator
38 |
39 | - [ ] Extend `TextValidator` to use the validator programmatically.
40 | - [ ] Extend `CustomValidator` to use the validator in XML.
41 |
42 | #### TextValidator
43 |
44 | ```kotlin
45 | class SuffixValidator(private val suffix: String, errorMessage: String) : TextValidator(errorMessage) {
46 | override fun isValid(text: String): Boolean = text.endsWith(suffix)
47 | }
48 | ```
49 | Use the validator
50 |
51 | ```java
52 | formEditText.addValidator(SuffixValidator("Must start with d."))
53 | ```
54 | **Note** `SuffixValidator` is predefined in the library.
55 |
56 | #### CustomValidator
57 | `CustomValidator` is a validator that enables you create a custom validator to be used in XML using `customValidationType` attribute.
58 |
59 | Define the custom validator by extending `CustomValidator`.
60 |
61 | ```java
62 | class NumberOneCustomValidator(errorMessage: String) : CustomValidator(errorMessage) {
63 | override fun customValidationType(context: Context): String {
64 | // use the type defined using non-translatable string to avoid mistakes
65 | return context.getString(R.string.custom_validator_number_one)
66 | }
67 | override fun isValid(text: String) = text == "1"
68 | }
69 | ```
70 |
71 | Declare `NumberOneCustomValidator` in XML
72 |
73 | ``` xml
74 |
76 | app:customValidationType="@string/custom_validator_number_one"
77 | ...
78 | />
79 | ```
80 |
81 | Register custom validators. Note that it's mandatory to register custom validators to be recognized by FormValidator.
82 |
83 | ```kotlin
84 | class App : Application() {
85 | override fun onCreate() {
86 | super.onCreate()
87 | TextViewValidators.customValidators = listOf(NumberOneCustomValidator("Value doesn't equal 1"))
88 | }
89 | }
90 | ```
91 |
92 |
93 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_form.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
17 |
18 |
26 |
27 |
30 |
31 |
39 |
40 |
43 |
44 |
52 |
53 |
56 |
57 |
65 |
66 |
69 |
70 |
75 |
76 |
79 |
80 |
84 |
85 |
88 |
89 |
95 |
96 |
99 |
100 |
108 |
109 |
112 |
113 |
117 |
118 |
121 |
122 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/core/src/main/java/com/sha/formvalidator/textview/DefTextValidationHandler.kt:
--------------------------------------------------------------------------------
1 | package com.sha.formvalidator.textview
2 |
3 | import android.content.Context
4 | import android.util.AttributeSet
5 | import android.widget.EditText
6 | import com.google.android.material.textfield.TextInputLayout
7 | import com.sha.formvalidator.R
8 | import com.sha.formvalidator.textview.validator.TextValidator
9 | import com.sha.formvalidator.textview.validator.composite.AndValidator
10 | import com.sha.formvalidator.textview.validator.composite.CompositeValidator
11 |
12 | /**
13 | * Default implementation of an [TextValidator]
14 | */
15 | class DefTextValidationHandler : TextValidationHandler {
16 | /**
17 | * The custom validators set using
18 | */
19 | private lateinit var mValidator: CompositeValidator
20 | lateinit var editText: EditText
21 |
22 | private val attrInfo = TextViewAttrInfo()
23 |
24 | override val isRequired: Boolean
25 | get() = attrInfo.required
26 |
27 | /**
28 | * support dynamic new DefaultEditTextValidator() ,used for Java call
29 | *
30 | * @param editText EditText
31 | * @param context Context
32 | */
33 | constructor(editText: EditText, context: Context) {
34 | setupDynamically(editText, context)
35 | }
36 |
37 | constructor(editText: EditText, attrs: AttributeSet, context: Context) {
38 | setupFromXml(editText, attrs, context)
39 | }
40 |
41 | private fun setupDynamically(editText: EditText, context: Context) {
42 | attrInfo.validationType = TextViewValidationType.NOT_EMPTY
43 | this.editText = editText
44 | setupValidator(context)
45 | }
46 |
47 | private fun setupFromXml(
48 | editText: EditText,
49 | attrs: AttributeSet,
50 | context: Context
51 | ) {
52 | setupAttrs(attrs, context)
53 | this.editText = editText
54 | setupValidator(context)
55 | }
56 |
57 | private fun setupAttrs(attrs: AttributeSet, context: Context) {
58 | val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FormEditText)
59 |
60 | attrInfo.required = typedArray.getBoolean(R.styleable.FormEditText_required, true)
61 |
62 | val validationTypeValue = typedArray.getInt(R.styleable.FormEditText_validationType, TextViewValidationType.NOT_DETECTABLE.value)
63 | attrInfo.validationType = TextViewValidationType.fromValue(validationTypeValue)
64 |
65 | attrInfo.errorMessage = typedArray.getString(R.styleable.FormEditText_errorMessage) ?: ""
66 | attrInfo.customValidationType = typedArray.getString(R.styleable.FormEditText_customValidationType) ?: ""
67 | attrInfo.regex = typedArray.getString(R.styleable.FormEditText_regex) ?: ""
68 | attrInfo.emptyErrorMessage = typedArray.getString(R.styleable.FormEditText_requiredErrorMessage) ?: ""
69 | attrInfo.dateFormat = typedArray.getString(R.styleable.FormEditText_dateFormat) ?: ""
70 |
71 | when (attrInfo.validationType) {
72 | TextViewValidationType.NUMERIC_RANGE -> {
73 | attrInfo.minNumber = typedArray.getInt(R.styleable.FormEditText_minNumber, Integer.MIN_VALUE)
74 | attrInfo.maxNumber = typedArray.getInt(R.styleable.FormEditText_maxNumber, Integer.MAX_VALUE)
75 | }
76 |
77 | TextViewValidationType.FLOAT_NUMERIC_RANGE -> {
78 | attrInfo.floatMinNumber = typedArray.getFloat(R.styleable.FormEditText_floatMinNumber, Float.MIN_VALUE)
79 | attrInfo.floatMaxNumber = typedArray.getFloat(R.styleable.FormEditText_floatMaxNumber, Float.MAX_VALUE)
80 | }
81 | else -> {}
82 | }
83 |
84 | typedArray.recycle()
85 | }
86 |
87 | override fun addValidator(validator: TextValidator) {
88 | mValidator.enqueue(validator)
89 | }
90 |
91 | override fun setupValidator(context: Context) {
92 | mValidator = AndValidator()
93 | addValidator(TextViewValidatorFactory.validator(attrInfo, context))
94 | }
95 |
96 | override fun validate(showError: Boolean): Boolean {
97 | val isValid = mValidator.isValid(editText.text.toString())
98 | if (!isValid && showError) showError()
99 | else if(isValid && showError){
100 | hideError()
101 | }
102 | return isValid
103 | }
104 |
105 | override fun showError() {
106 | if (!mValidator.hasErrorMessage()) return
107 |
108 | if (hasTextInputLayout()) {
109 | textInputLayout().error = mValidator.errorMessage
110 | return
111 | }
112 |
113 | editText.error = mValidator.errorMessage
114 | }
115 |
116 | override fun hideError() {
117 | if (hasTextInputLayout()) {
118 | textInputLayout().error = null
119 | return
120 | }
121 |
122 | editText.error = null
123 | }
124 |
125 | private fun hasTextInputLayout(): Boolean {
126 | val parent = editText.parent.parent
127 | return parent is TextInputLayout
128 | }
129 |
130 | private fun textInputLayout(): TextInputLayout {
131 | return editText.parent.parent as TextInputLayout
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Form Validator
4 |
5 | Options
6 |
7 | Validate!
8 | The numeric field allows only numbers on it. The previous EditText was intentionally configured to accept any kind of input so that you can test the validation.
9 | The alpha field will check if the field contains only standard letters.
10 | This field will check for valid person name OR surname
11 | This field will check for valid person name AND surname
12 |
13 |
14 | This field will check date/datetime
15 |
16 |
17 | This field will check yyyy-MM-dd
18 |
19 | me@andreabaccega.com
20 | The email field will only accept valid email input.\nNote that this will only perform a regular expression check
21 |
22 | 444433332222111
23 | The credit card field will only accept valid credit card numbers. The validation is performed through the Luhn Algorithm
24 |
25 | +41 01 12345678
26 | The phone number will be validated using regex It will allow several formats.\n\t- +00 01 23456799\n\t- 0123456789
27 |
28 | google.com
29 | Domain name check will be performed using regex.
30 |
31 | 127.0.0.1
32 | The ip address check will be performed using regex.
33 |
34 | https://www.google.com/
35 | The check will be performed using regex only.
36 |
37 | …
38 |
39 | This is a regular phone check ( like the previous one ).\nThe only difference is that here we\'ve a custom message for the empty case and the invalid case. Try it out!
40 | Custom test error message!
41 | Custom empty error message!
42 |
43 | This fields validates a phone when the user enters something. If the user doesn\'t enter any data the EditText will validate!
44 |
45 | aa
46 | This field only validates with 2 or more "a"
47 | The field validates only if the field content matches the regex given in the xml. The current regex is: /^[a]{2,}$/\nNote that the regex is case sensitive so that the field won\'t validate if you enter "AA"
48 |
49 | You should enter \'wow\' here
50 | The current check is performed by a programmatically added validator. Check out the source code.
51 | Programmatically added validator
52 | Validator in this field is defined as \n \n "app:customValidationType="@string/custom_validator_number_one" \n \nand the validator class is NumberOneCustomValidator.
53 |
54 | Email OR Credit
55 | your email or credit card number
56 | The previous field will validate only if it is not empty and one of the following is true:\n- it is a valid email address.\n- it is a valid credit card
57 |
58 | Full Name
59 | eg Sha Ka
60 | Address
61 | House number, Street, Suburb, Postcode
62 | Phone number
63 | Your phone number
64 | email@address.com
65 | Email
66 | The entered phone number is invalid
67 | Full name is invalid (must be at least 2 space separated names)
68 | A contact number is required
69 | A full name is required
70 | Provided e-mail address is invalid
71 | The numeric field allows only numbers.
72 | Password must match.
73 | Passwords Match
74 |
75 |
76 | Select Country
77 | Malaysia
78 | United States
79 | Indonesia
80 | France
81 | Italy
82 | Singapore
83 | New Zealand
84 | India
85 |
86 |
87 |
88 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | CFPropertyList (3.0.3)
5 | addressable (2.7.0)
6 | public_suffix (>= 2.0.2, < 5.0)
7 | artifactory (3.0.15)
8 | atomos (0.1.3)
9 | aws-eventstream (1.1.1)
10 | aws-partitions (1.434.0)
11 | aws-sdk-core (3.113.0)
12 | aws-eventstream (~> 1, >= 1.0.2)
13 | aws-partitions (~> 1, >= 1.239.0)
14 | aws-sigv4 (~> 1.1)
15 | jmespath (~> 1.0)
16 | aws-sdk-kms (1.43.0)
17 | aws-sdk-core (~> 3, >= 3.112.0)
18 | aws-sigv4 (~> 1.1)
19 | aws-sdk-s3 (1.92.0)
20 | aws-sdk-core (~> 3, >= 3.112.0)
21 | aws-sdk-kms (~> 1)
22 | aws-sigv4 (~> 1.1)
23 | aws-sigv4 (1.2.3)
24 | aws-eventstream (~> 1, >= 1.0.2)
25 | babosa (1.0.4)
26 | claide (1.0.3)
27 | colored (1.2)
28 | colored2 (3.1.2)
29 | commander-fastlane (4.4.6)
30 | highline (~> 1.7.2)
31 | declarative (0.0.20)
32 | declarative-option (0.1.0)
33 | digest-crc (0.6.3)
34 | rake (>= 12.0.0, < 14.0.0)
35 | domain_name (0.5.20190701)
36 | unf (>= 0.0.5, < 1.0.0)
37 | dotenv (2.7.6)
38 | emoji_regex (3.2.2)
39 | excon (0.79.0)
40 | faraday (1.3.0)
41 | faraday-net_http (~> 1.0)
42 | multipart-post (>= 1.2, < 3)
43 | ruby2_keywords
44 | faraday-cookie_jar (0.0.7)
45 | faraday (>= 0.8.0)
46 | http-cookie (~> 1.0.0)
47 | faraday-net_http (1.0.1)
48 | faraday_middleware (1.0.0)
49 | faraday (~> 1.0)
50 | fastimage (2.2.3)
51 | fastlane (2.178.0)
52 | CFPropertyList (>= 2.3, < 4.0.0)
53 | addressable (>= 2.3, < 3.0.0)
54 | artifactory (~> 3.0)
55 | aws-sdk-s3 (~> 1.0)
56 | babosa (>= 1.0.3, < 2.0.0)
57 | bundler (>= 1.12.0, < 3.0.0)
58 | colored
59 | commander-fastlane (>= 4.4.6, < 5.0.0)
60 | dotenv (>= 2.1.1, < 3.0.0)
61 | emoji_regex (>= 0.1, < 4.0)
62 | excon (>= 0.71.0, < 1.0.0)
63 | faraday (~> 1.0)
64 | faraday-cookie_jar (~> 0.0.6)
65 | faraday_middleware (~> 1.0)
66 | fastimage (>= 2.1.0, < 3.0.0)
67 | gh_inspector (>= 1.1.2, < 2.0.0)
68 | google-api-client (>= 0.37.0, < 0.39.0)
69 | google-cloud-storage (>= 1.15.0, < 2.0.0)
70 | highline (>= 1.7.2, < 2.0.0)
71 | json (< 3.0.0)
72 | jwt (>= 2.1.0, < 3)
73 | mini_magick (>= 4.9.4, < 5.0.0)
74 | multipart-post (~> 2.0.0)
75 | naturally (~> 2.2)
76 | plist (>= 3.1.0, < 4.0.0)
77 | rubyzip (>= 2.0.0, < 3.0.0)
78 | security (= 0.1.3)
79 | simctl (~> 1.6.3)
80 | slack-notifier (>= 2.0.0, < 3.0.0)
81 | terminal-notifier (>= 2.0.0, < 3.0.0)
82 | terminal-table (>= 1.4.5, < 2.0.0)
83 | tty-screen (>= 0.6.3, < 1.0.0)
84 | tty-spinner (>= 0.8.0, < 1.0.0)
85 | word_wrap (~> 1.0.0)
86 | xcodeproj (>= 1.13.0, < 2.0.0)
87 | xcpretty (~> 0.3.0)
88 | xcpretty-travis-formatter (>= 0.0.3)
89 | gh_inspector (1.1.3)
90 | google-api-client (0.38.0)
91 | addressable (~> 2.5, >= 2.5.1)
92 | googleauth (~> 0.9)
93 | httpclient (>= 2.8.1, < 3.0)
94 | mini_mime (~> 1.0)
95 | representable (~> 3.0)
96 | retriable (>= 2.0, < 4.0)
97 | signet (~> 0.12)
98 | google-apis-core (0.3.0)
99 | addressable (~> 2.5, >= 2.5.1)
100 | googleauth (~> 0.14)
101 | httpclient (>= 2.8.1, < 3.0)
102 | mini_mime (~> 1.0)
103 | representable (~> 3.0)
104 | retriable (>= 2.0, < 4.0)
105 | rexml
106 | signet (~> 0.14)
107 | webrick
108 | google-apis-iamcredentials_v1 (0.2.0)
109 | google-apis-core (~> 0.1)
110 | google-apis-storage_v1 (0.3.0)
111 | google-apis-core (~> 0.1)
112 | google-cloud-core (1.6.0)
113 | google-cloud-env (~> 1.0)
114 | google-cloud-errors (~> 1.0)
115 | google-cloud-env (1.5.0)
116 | faraday (>= 0.17.3, < 2.0)
117 | google-cloud-errors (1.1.0)
118 | google-cloud-storage (1.31.0)
119 | addressable (~> 2.5)
120 | digest-crc (~> 0.4)
121 | google-apis-iamcredentials_v1 (~> 0.1)
122 | google-apis-storage_v1 (~> 0.1)
123 | google-cloud-core (~> 1.2)
124 | googleauth (~> 0.9)
125 | mini_mime (~> 1.0)
126 | googleauth (0.16.0)
127 | faraday (>= 0.17.3, < 2.0)
128 | jwt (>= 1.4, < 3.0)
129 | memoist (~> 0.16)
130 | multi_json (~> 1.11)
131 | os (>= 0.9, < 2.0)
132 | signet (~> 0.14)
133 | highline (1.7.10)
134 | http-cookie (1.0.3)
135 | domain_name (~> 0.5)
136 | httpclient (2.8.3)
137 | jmespath (1.4.0)
138 | json (2.5.1)
139 | jwt (2.2.2)
140 | memoist (0.16.2)
141 | mini_magick (4.11.0)
142 | mini_mime (1.0.2)
143 | multi_json (1.15.0)
144 | multipart-post (2.0.0)
145 | nanaimo (0.3.0)
146 | naturally (2.2.1)
147 | os (1.1.1)
148 | plist (3.6.0)
149 | public_suffix (4.0.6)
150 | rake (13.0.3)
151 | representable (3.0.4)
152 | declarative (< 0.1.0)
153 | declarative-option (< 0.2.0)
154 | uber (< 0.2.0)
155 | retriable (3.1.2)
156 | rexml (3.2.5)
157 | rouge (2.0.7)
158 | ruby2_keywords (0.0.4)
159 | rubyzip (2.3.0)
160 | security (0.1.3)
161 | signet (0.15.0)
162 | addressable (~> 2.3)
163 | faraday (>= 0.17.3, < 2.0)
164 | jwt (>= 1.5, < 3.0)
165 | multi_json (~> 1.10)
166 | simctl (1.6.8)
167 | CFPropertyList
168 | naturally
169 | slack-notifier (2.3.2)
170 | terminal-notifier (2.0.0)
171 | terminal-table (1.8.0)
172 | unicode-display_width (~> 1.1, >= 1.1.1)
173 | tty-cursor (0.7.1)
174 | tty-screen (0.8.1)
175 | tty-spinner (0.9.3)
176 | tty-cursor (~> 0.7)
177 | uber (0.1.0)
178 | unf (0.1.4)
179 | unf_ext
180 | unf_ext (0.0.7.7)
181 | unicode-display_width (1.7.0)
182 | webrick (1.7.0)
183 | word_wrap (1.0.0)
184 | xcodeproj (1.19.0)
185 | CFPropertyList (>= 2.3.3, < 4.0)
186 | atomos (~> 0.1.3)
187 | claide (>= 1.0.2, < 2.0)
188 | colored2 (~> 3.1)
189 | nanaimo (~> 0.3.0)
190 | xcpretty (0.3.0)
191 | rouge (~> 2.0.7)
192 | xcpretty-travis-formatter (1.0.1)
193 | xcpretty (~> 0.2, >= 0.0.7)
194 |
195 | PLATFORMS
196 | ruby
197 |
198 | DEPENDENCIES
199 | fastlane
200 |
201 | BUNDLED WITH
202 | 2.1.4
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
FormValidator
3 |
The easiest, most clean Android form validation.
4 |
5 |
6 |
7 |
8 |
9 |
10 | A declarative Form Validation for Android, simple, clean, and customizable.
11 |
12 | Every time you create a form, you need to declare fields and write code for for validating each field in the form, and this results in many ```if else``` and a lot of boilerplate. For these reasons **FormValidator** is here, just declare your fields in XML and its validation and all things will be done for you!
13 |
14 |
15 |
16 | # Table of contents
17 |
18 | - [Usage](#usage)
19 | - [Installation](#installation)
20 | - [Widgets](#widgets)
21 | - [TextView Widgets](#textview-widgets)
22 | - [Other Widgets](#other-widgets)
23 | - [Validatable interface](#validatable-interface)
24 | - [Form Layout](#form-layout)
25 | - [TextView Validation](#textview-validation)
26 | - [Credit](#credit)
27 | - [License](#-license)
28 |
29 | # Usage
30 | ```xml
31 |
32 |
35 |
36 |
39 |
40 |
43 |
44 |
47 |
48 | ```
49 |
50 | To trigger validation:
51 |
52 | ```kotlin
53 | val isFormValid = findViewById