├── .gitignore ├── .idea ├── .gitignore ├── compiler.xml ├── gradle.xml ├── misc.xml └── vcs.xml ├── FormValidator ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── initbase │ │ └── formvalidator │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── initbase │ │ └── formvalidator │ │ ├── Components.kt │ │ └── FormValidator.kt │ └── test │ └── java │ └── com │ └── initbase │ └── formvalidator │ └── ExampleUnitTest.kt ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── initbase │ │ └── formvalidatorlibrary │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── initbase │ │ │ └── formvalidatorlibrary │ │ │ ├── MainActivity.kt │ │ │ └── ui │ │ │ ├── components │ │ │ └── FormComponents.kt │ │ │ └── theme │ │ │ ├── Color.kt │ │ │ ├── Shape.kt │ │ │ ├── Theme.kt │ │ │ └── Type.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.webp │ │ └── ic_launcher_round.webp │ │ ├── values-night │ │ └── themes.xml │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ └── test │ └── java │ └── com │ └── initbase │ └── formvalidatorlibrary │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /FormValidator/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /FormValidator/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'kotlin-android' 4 | id 'maven-publish' 5 | } 6 | 7 | def compose_version = '1.0.1' 8 | android { 9 | compileSdk 31 10 | 11 | defaultConfig { 12 | minSdk 21 13 | targetSdk 31 14 | versionCode 1 15 | versionName "1.0" 16 | 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | consumerProguardFiles "consumer-rules.pro" 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_1_8 29 | targetCompatibility JavaVersion.VERSION_1_8 30 | } 31 | kotlinOptions { 32 | jvmTarget = '1.8' 33 | } 34 | buildFeatures { 35 | compose true 36 | } 37 | composeOptions { 38 | kotlinCompilerExtensionVersion compose_version 39 | kotlinCompilerVersion '1.5.21' 40 | } 41 | } 42 | 43 | dependencies { 44 | implementation "androidx.compose.ui:ui:$compose_version" 45 | implementation "androidx.compose.ui:ui-tooling:$compose_version" 46 | implementation "androidx.compose.foundation:foundation:$compose_version" 47 | implementation "androidx.compose.foundation:foundation-layout:$compose_version" 48 | implementation "androidx.compose.material:material:$compose_version" 49 | implementation "androidx.compose.runtime:runtime:$compose_version" 50 | implementation "androidx.compose.runtime:runtime-livedata:$compose_version" 51 | implementation "androidx.compose.animation:animation:$compose_version" 52 | } 53 | 54 | afterEvaluate { 55 | publishing { 56 | publications { 57 | release(MavenPublication) { 58 | from components.release 59 | 60 | groupId = 'com.github.funyin' 61 | artifactId = 'formvalidator' 62 | version = '1.0' 63 | } 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /FormValidator/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/FormValidator/consumer-rules.pro -------------------------------------------------------------------------------- /FormValidator/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /FormValidator/src/androidTest/java/com/initbase/formvalidator/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidator 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.initbase.formvalidator.test", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /FormValidator/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /FormValidator/src/main/java/com/initbase/formvalidator/Components.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidator 2 | 3 | import androidx.compose.animation.* 4 | import androidx.compose.foundation.layout.* 5 | import androidx.compose.foundation.shape.RoundedCornerShape 6 | import androidx.compose.material.MaterialTheme 7 | import androidx.compose.material.Surface 8 | import androidx.compose.material.Text 9 | import androidx.compose.runtime.* 10 | import androidx.compose.runtime.livedata.observeAsState 11 | import androidx.compose.ui.Alignment 12 | import androidx.compose.ui.Modifier 13 | import androidx.compose.ui.graphics.Color 14 | import androidx.compose.ui.graphics.Shape 15 | import androidx.compose.ui.text.TextStyle 16 | import androidx.compose.ui.text.font.FontWeight 17 | import androidx.compose.ui.unit.dp 18 | import androidx.compose.ui.unit.sp 19 | import kotlinx.coroutines.delay 20 | import kotlinx.coroutines.launch 21 | import kotlin.time.Duration 22 | import kotlin.time.ExperimentalTime 23 | 24 | @Composable 25 | fun Form( 26 | modifier: Modifier = Modifier, 27 | validator: FormValidator = FormValidator(), 28 | content: @Composable ColumnScope.() -> Unit = {} 29 | ) { 30 | CompositionLocalProvider(LocalFormValidator provides validator) { 31 | Column(content = content, modifier = modifier) 32 | } 33 | } 34 | 35 | /** 36 | * Overload of [Form] that shows a snack bar with validation error. 37 | * Suggestion -> When this overload is used, do not show the error for each field in the form with 38 | * [FormValidator.ValidationField.onError] since the purpose of this form is to show one error at a time. 39 | * 40 | * 41 | *@param modifier Modifier for the Form i.e **Column** 42 | *@param snackBarProperties The properties([SnackBarProperties]) for the snackbar that is shown when the form fails validation 43 | *@param lifecycleOwner Used to observe validation and dispose observer 44 | *@param validator The [FormValidator] that controls the form. 45 | */ 46 | @OptIn(ExperimentalAnimationApi::class, ExperimentalTime::class) 47 | @Composable 48 | fun Form( 49 | modifier: Modifier = Modifier, 50 | validator: FormValidator = FormValidator(), 51 | snackBarProperties: SnackBarProperties = SnackBarProperties(), 52 | content: @Composable ColumnScope.() -> Unit = {} 53 | ) { 54 | var showError by remember { mutableStateOf(false) } 55 | val scope = rememberCoroutineScope() 56 | validator.onValidate = { 57 | if (!it) { 58 | scope.launch { 59 | showError = true 60 | delay(snackBarProperties.visibleDuration) 61 | showError = false 62 | } 63 | } 64 | } 65 | CompositionLocalProvider(LocalFormValidator provides validator) { 66 | Box(contentAlignment = Alignment.BottomCenter) { 67 | Column(content = content, modifier = modifier) 68 | AnimatedVisibility( 69 | visible = showError, 70 | enter = snackBarProperties.enterTransition, 71 | exit = snackBarProperties.exitTransition 72 | ) { 73 | ValidationSnackBar(snackBarProperties.copy(message = validator.errorMessage)) 74 | } 75 | } 76 | } 77 | } 78 | 79 | /** 80 | * SnackBar properties for [Form] 81 | */ 82 | data class SnackBarProperties @OptIn( 83 | ExperimentalTime::class, 84 | ExperimentalAnimationApi::class 85 | ) constructor( 86 | var message: String? = null, 87 | val title: String = "Validation Error", 88 | val modifier: Modifier = Modifier.fillMaxWidth(), 89 | val margin: PaddingValues = PaddingValues(16.dp), 90 | val titleStyle: TextStyle? = null, 91 | val messageStyle: TextStyle? = null, 92 | val backgroundColor: Color? = null, 93 | val shape: Shape = RoundedCornerShape(8.dp), 94 | val visibleDuration: Duration = Duration.milliseconds(3000), 95 | val enterTransition: EnterTransition = fadeIn() + expandIn(), 96 | val exitTransition: ExitTransition = shrinkOut() + fadeOut() 97 | ) 98 | 99 | @Composable 100 | private fun ValidationSnackBar(properties: SnackBarProperties) { 101 | Box(contentAlignment = Alignment.Center, modifier = Modifier.padding(properties.margin)) { 102 | Surface( 103 | color = properties.backgroundColor ?: MaterialTheme.colors.surface, 104 | shape = properties.shape, 105 | modifier = properties.modifier, 106 | ) { 107 | Column(modifier = Modifier.padding(16.dp)) { 108 | Text( 109 | text = properties.title, 110 | modifier = Modifier.padding(bottom = 5.dp), 111 | style = properties.titleStyle ?: TextStyle( 112 | color = MaterialTheme.colors.error, 113 | fontSize = 11.sp, 114 | fontWeight = FontWeight.W600, 115 | ) 116 | ) 117 | val message = properties.message 118 | if (message != null) 119 | Text( 120 | text = message, 121 | style = properties.messageStyle 122 | ?: TextStyle(color = MaterialTheme.colors.onSurface) 123 | ) 124 | } 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /FormValidator/src/main/java/com/initbase/formvalidator/FormValidator.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidator 2 | 3 | import androidx.compose.runtime.compositionLocalOf 4 | import androidx.compose.runtime.getValue 5 | import androidx.compose.runtime.mutableStateOf 6 | import androidx.compose.runtime.setValue 7 | import androidx.lifecycle.MutableLiveData 8 | import com.initbase.formvalidator.FormValidator.Flow.* 9 | import com.initbase.formvalidator.FormValidator.Type.* 10 | import java.util.regex.Pattern 11 | 12 | /** 13 | * Used to reference the validator in nested components. 14 | * ```LocalFormValidator.current``` 15 | * */ 16 | val LocalFormValidator = compositionLocalOf { FormValidator() } 17 | typealias validationField = FormValidator.ValidationField<*> 18 | typealias customValidationResponse = Pair 19 | 20 | /** 21 | * @property errorMessage The error message of the first or last field validation based on the [Flow]. When [flow] is [Flow.Splash] this field is [Flow.fallbackErrorMessage] 22 | * @property onValidate CallBack invoked after validation with result. This is an internal call back for the library, use [valid] 23 | * @property valid Observe to get notified on validation changes 24 | * */ 25 | class FormValidator(val fields: List = emptyList(), val flow: Flow = Down) { 26 | var onValidate: (Boolean) -> Unit = {} 27 | var errorMessage by mutableStateOf(null) 28 | val valid = MutableLiveData() 29 | 30 | /** 31 | * Describes the direction and type of validation in the form 32 | * @param fallbackErrorMessage The error message for the form in the case of [Flow.Splash] 33 | * */ 34 | enum class Flow(val fallbackErrorMessage: String = "Fill all required fields") { 35 | /** 36 | * The form is validated from top to bottom and the first field that is invalid causes the form to be invalid. 37 | * [FormValidator.errorMessage] is set to the error message of the first invalid item 38 | * */ 39 | Down, 40 | 41 | /** 42 | * The form is validated from bottom to top and the last field that is invalid causes the form to be invalid. 43 | * [FormValidator.errorMessage] is set to the error message of the first invalid item 44 | * */ 45 | Up, 46 | 47 | /** 48 | * All fields are validated at once and each field([ValidationField]) invokes [ValidationField.onError]. 49 | * [FormValidator.errorMessage] is set to null 50 | * */ 51 | Splash 52 | } 53 | 54 | /** 55 | * The Type of validation to perform on [ValidationField] 56 | * */ 57 | sealed class Type { 58 | /** 59 | * Value provided to validation field must not be null. 60 | * 61 | * In the case of [String] the value must also not be blank 62 | * */ 63 | object Required : Type() 64 | 65 | /** 66 | * Value provided to validation field must. 67 | * 68 | * In the case of [String] the value character length must be greater than[template]. 69 | * 70 | * In the case of [Number] the value must be greater than [template]. 71 | * 72 | * Returns false for other cases 73 | * @param T The type parameter of the [ValidationField] 74 | * @property template The value that is used to validate the value provided to the [ValidationField] 75 | * */ 76 | data class MustBeMoreThan(val template: T) : Type() 77 | 78 | /** 79 | * Value provided to validation field must. 80 | * 81 | * In the case of [String] the value character length less than [template]. 82 | * 83 | * In the case of [Number] the value must be greater than [template]. 84 | * 85 | * Returns false for other cases 86 | * @param T The type parameter of the [ValidationField] 87 | * @property template The value that is used to validate the value provided to the [ValidationField] 88 | * */ 89 | data class MustBeLessThan(val template: T) : Type() 90 | 91 | /** 92 | * Value provided to [ValidationField]. 93 | * 94 | * In the case of [Number] be between([min] and [max] inclusive) [min] and [max]. 95 | * 96 | * Returns false for other cases 97 | * @property min The minimum value of the [ValidationField] 98 | * @property max The maximum value of the [ValidationField] 99 | * */ 100 | data class MustBeInRange( 101 | val min: Number = 0, 102 | val max: Number = 100 103 | ) : Type() 104 | 105 | /** 106 | * Value provided to validation field is validated base on equality. 107 | * 108 | * In the case of [String] 109 | * - if [template] is [String]=> value must match [template] 110 | * - if [template] is [Number] => value character length must be equal to [template] 111 | * 112 | * In the case os [Number] 113 | * - value must be equal to the [Number] value of template 114 | * 115 | * In the case of [Object] (Custom class) 116 | * - value must be equal to [template] 117 | * 118 | * returns false for other cases 119 | * @param T The type parameter of the [ValidationField] 120 | * @property template The value that is used to validate the value provided to the [ValidationField] 121 | * */ 122 | data class MustBeEqualTo(val template: T) : Type() 123 | 124 | /** 125 | * Implement your own validation logic. 126 | * @param valid A callback that provides the value of the validation field and returns a pair of values. 127 | * 128 | * [Pair.first]=> The result of your validation 129 | * 130 | * [Pair.second]=> The errorMessage of your validation. Return null if validation passes 131 | * */ 132 | data class Custom(val valid: ((T) -> customValidationResponse)) : Type() 133 | 134 | /** 135 | * Validates that the value provided to [ValidationField] matches and email patters 136 | */ 137 | object Email : Type() 138 | 139 | /** 140 | * Value is always valid. Always returns true. 141 | */ 142 | object Optional : Type() 143 | } 144 | 145 | 146 | /** 147 | * Corresponds to a field in a form and performs validation on the fields value 148 | * @param value The field value to be validated 149 | * @param name The the Field name, it is added to the error message to make it more descriptive. e.g 'Address is not valid' 150 | * @param type The type of validation that would be performed on this field. see [Type] 151 | * @param onError Callback that provides error message of validation. Called twice, 152 | * - First before validation to reset error state 153 | * - Second after validation to provide error message 154 | * */ 155 | class ValidationField( 156 | val value: T? = null, 157 | var name: String = "Field", 158 | val type: Type = Required, 159 | val onError: (String?) -> Unit = {} 160 | ) { 161 | var errorMessage: String? = null 162 | private set 163 | private val EMAIL_ADDRESS_PATTERN: Pattern = 164 | Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+") 165 | 166 | fun valid(): Boolean { 167 | val valid: Boolean 168 | var defaultErrorMessage: String? = "$name is not Valid" 169 | valid = if (value == null && type != Optional) { 170 | defaultErrorMessage = "$name is required" 171 | false 172 | } else 173 | when (value) { 174 | is String -> { 175 | when (type) { 176 | Required -> { 177 | defaultErrorMessage = "$name is required" 178 | value.isNotBlank() 179 | } 180 | is MustBeMoreThan -> { 181 | val length = type.template.toString().length 182 | defaultErrorMessage = 183 | "$name must be longer than $length characters" 184 | value.length > length 185 | } 186 | is MustBeLessThan -> { 187 | val length = type.template.toString().length 188 | defaultErrorMessage = 189 | "$name must be shorter than $length characters" 190 | value.length < length 191 | } 192 | is MustBeInRange -> { 193 | defaultErrorMessage = 194 | "$name must be in range ${type.min} - ${type.max}" 195 | false 196 | } 197 | is MustBeEqualTo -> { 198 | val template = type.template 199 | when (template) { 200 | is String -> { 201 | defaultErrorMessage = "$name must match to $template" 202 | value == template 203 | } 204 | is Number -> { 205 | val length = template.toString().length 206 | defaultErrorMessage = "$name must be $length characters" 207 | value.length == length 208 | } 209 | else -> { 210 | defaultErrorMessage = "$name is not valid" 211 | false 212 | } 213 | } 214 | } 215 | Email -> { 216 | defaultErrorMessage = if (value.isEmpty()) 217 | "Enter a valid email" 218 | else 219 | "$value is not a valid email" 220 | EMAIL_ADDRESS_PATTERN.matcher(value).matches() 221 | } 222 | is Custom -> { 223 | val response = type.valid.invoke(value) 224 | defaultErrorMessage = response.second 225 | response.first 226 | } 227 | Optional -> true 228 | } 229 | } 230 | is Number -> { 231 | when (type) { 232 | Required -> { 233 | defaultErrorMessage = "$name is required" 234 | false 235 | } 236 | is MustBeMoreThan -> { 237 | val template = (type.template.toString()).toFloatOrNull() ?: 0f 238 | defaultErrorMessage = "$name must be greater than $template" 239 | value.toFloat() > template 240 | } 241 | is MustBeLessThan -> { 242 | val template = type.template 243 | defaultErrorMessage = "$name must be less than $template" 244 | if (template is Number) { 245 | value.toFloat() < template.toFloat() 246 | } else 247 | false 248 | } 249 | is MustBeInRange -> { 250 | defaultErrorMessage = 251 | "$name must be in range ${type.min} - ${type.max}" 252 | val mValue = value.toFloat() 253 | mValue >= type.min.toFloat() && mValue <= type.max.toFloat() 254 | } 255 | is MustBeEqualTo -> { 256 | val template = (type.template.toString()).toFloatOrNull() ?: 0f 257 | defaultErrorMessage = "$name must be equal to $template" 258 | value == template 259 | } 260 | Email -> { 261 | defaultErrorMessage = "$name is not valid" 262 | false 263 | } 264 | Optional -> 265 | true 266 | is Custom -> { 267 | val response = type.valid.invoke(value) 268 | defaultErrorMessage = response.second 269 | response.first 270 | } 271 | } 272 | } 273 | //Field Type is not String or Number 274 | else -> { 275 | when (type) { 276 | Required -> { 277 | defaultErrorMessage = "$name is required" 278 | value != null 279 | } 280 | Email -> { 281 | defaultErrorMessage = "$name is not valid" 282 | false 283 | } 284 | is MustBeEqualTo -> { 285 | defaultErrorMessage = "$name does not match template" 286 | value == type.template 287 | } 288 | is MustBeInRange -> { 289 | defaultErrorMessage = 290 | "$name must be in range ${type.min} - ${type.max}" 291 | false 292 | } 293 | is MustBeLessThan -> { 294 | defaultErrorMessage = "$name must be less than ${type.template}" 295 | false 296 | } 297 | is MustBeMoreThan -> { 298 | defaultErrorMessage = 299 | "$name must be greater than ${type.template}" 300 | false 301 | } 302 | Optional -> true 303 | is Custom -> { 304 | val response = type.valid.invoke(value) 305 | defaultErrorMessage = response.second 306 | response.first 307 | } 308 | } 309 | } 310 | } 311 | if (errorMessage == null) 312 | errorMessage = defaultErrorMessage 313 | onError.invoke( 314 | if (valid) 315 | null 316 | else errorMessage 317 | ) 318 | return valid 319 | } 320 | } 321 | 322 | /** 323 | * Invokes validation on each field in the form. 324 | * @return **True** if all fields are valid and **false** otherwise 325 | * */ 326 | fun validate(): Boolean { 327 | var valid = true 328 | errorMessage = null 329 | //reset the error state of each field 330 | fields.forEach { 331 | it.onError.invoke(null) 332 | } 333 | val invalidField: ValidationField<*>? = when (flow) { 334 | Down -> { 335 | fields.firstOrNull { 336 | !it.valid() 337 | } 338 | } 339 | Up -> { 340 | fields.lastOrNull { 341 | !it.valid() 342 | } 343 | } 344 | Splash -> { 345 | val results = mutableListOf() 346 | fields.forEach { 347 | results.add(it.valid()) 348 | } 349 | valid = results.all { it } 350 | fields.firstOrNull() 351 | } 352 | } 353 | invalidField?.let { 354 | errorMessage = if (flow == Splash) 355 | flow.fallbackErrorMessage 356 | else 357 | it.errorMessage 358 | valid = false 359 | } 360 | onValidate.invoke(valid) 361 | this.valid.postValue(valid) 362 | return valid 363 | } 364 | } -------------------------------------------------------------------------------- /FormValidator/src/test/java/com/initbase/formvalidator/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidator 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2021] [Funyinoluwa Kashimawo] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FormValidator [![](https://jitpack.io/v/funyin/FormValidator.svg)](https://jitpack.io/#funyin/FormValidator) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-FormValidator-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/8353) [![Made in Nigeria](https://img.shields.io/badge/made%20in-nigeria-008751.svg?style=flat-square)](https://github.com/acekyd/made-in-nigeria) 2 | A form validation library for android jetpack compose 3 | 4 | ## Features 5 | - Determine Validation Flow. 6 | __Flow.Down__|__Flow.Up__|__Flow.Splash__ 7 | - Custom Validation 8 | - Validation Snackbar 9 | - Validation State Callbacks 10 | - Library is well documented 11 | 12 | ## Preview 13 | 14 | 15 | https://user-images.githubusercontent.com/38915569/149603789-1f47436b-b8f9-44a6-98a6-6ec389a75e7b.mp4 16 | 17 | 18 | 19 | ## Example 20 | ```kotlin 21 | @Composable 22 | fun ScreenContent() { 23 | var name by remember { mutableStateOf("") } 24 | var nameError by remember { mutableStateOf(null) } 25 | var email by remember { mutableStateOf("") } 26 | var emailError by remember { mutableStateOf(null) } 27 | val nameField = "Name" 28 | val emailField = "Email" 29 | val validator = FormValidator( 30 | fields = listOf( 31 | ValidationField( 32 | value = name, 33 | name = nameField, 34 | onError = { 35 | nameError = it 36 | }), 37 | ValidationField( 38 | value = email, 39 | onError = { 40 | emailError = it 41 | }, type = FormValidator.Type.Email 42 | ) 43 | ) 44 | ) 45 | Form( 46 | validator = validator, 47 | modifier = Modifier 48 | .fillMaxSize() 49 | .verticalScroll(state = rememberScrollState()) 50 | .padding(16.dp) 51 | ) { 52 | Spacer(modifier = Modifier.height(30.dp)) 53 | AppTextField( 54 | label = nameField, 55 | value = name, 56 | placeholder = "Enter name", 57 | onValueChanged = { name = it }, 58 | errorMessage = nameError 59 | ) 60 | Spacer(modifier = Modifier.height(16.dp)) 61 | AppTextField( 62 | label = emailField, 63 | value = email, 64 | placeholder = "Enter email", 65 | onValueChanged = { email = it }, 66 | errorMessage = emailError, 67 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) 68 | ) 69 | Spacer(modifier = Modifier.height(40.dp)) 70 | AppButton(text = "Submit") { 71 | if(validator.validate()) 72 | showToast(validator.errorMessage) 73 | } 74 | } 75 | } 76 | ``` 77 | 78 | ## Getting started 79 | ### Step 1. Add the JitPack repository to your build file 80 | ```gradle 81 | allprojects { 82 | repositories { 83 | ... 84 | maven { url 'https://jitpack.io' } 85 | } 86 | } 87 | ``` 88 | 89 | ### Step 2. Add the dependency 90 | ```gradle 91 | dependencies { 92 | implementation 'com.github.funyin:FormValidator:1.0.0' 93 | } 94 | ``` 95 | 96 | [![BuyMeAShawrma.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1619907239535/KqJOyu-70.png)](https://www.buymeacoffee.com/funyinkash) 97 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | compileSdk 31 8 | 9 | defaultConfig { 10 | applicationId "com.initbase.formvalidatorlibrary" 11 | minSdk 21 12 | targetSdk 31 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | vectorDrawables { 18 | useSupportLibrary true 19 | } 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | compileOptions { 29 | sourceCompatibility JavaVersion.VERSION_1_8 30 | targetCompatibility JavaVersion.VERSION_1_8 31 | } 32 | kotlinOptions { 33 | jvmTarget = '1.8' 34 | useIR = true 35 | } 36 | buildFeatures { 37 | compose true 38 | } 39 | composeOptions { 40 | kotlinCompilerExtensionVersion compose_version 41 | kotlinCompilerVersion '1.5.21' 42 | } 43 | packagingOptions { 44 | resources { 45 | excludes += '/META-INF/{AL2.0,LGPL2.1}' 46 | } 47 | } 48 | } 49 | 50 | dependencies { 51 | implementation 'androidx.core:core-ktx:1.7.0' 52 | implementation 'androidx.appcompat:appcompat:1.4.0' 53 | implementation 'com.google.android.material:material:1.4.0' 54 | implementation "androidx.compose.ui:ui:$compose_version" 55 | implementation "androidx.compose.material:material:$compose_version" 56 | implementation "androidx.compose.ui:ui-tooling-preview:$compose_version" 57 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0' 58 | implementation 'androidx.activity:activity-compose:1.4.0' 59 | testImplementation 'junit:junit:4.+' 60 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 61 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 62 | androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version" 63 | debugImplementation "androidx.compose.ui:ui-tooling:$compose_version" 64 | // implementation project(':formvalidator') 65 | implementation 'com.github.funyin:FormValidator:1.0.0' 66 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/initbase/formvalidatorlibrary/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.initbase.formvalidatorlibrary", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary 2 | 3 | import android.os.Bundle 4 | import androidx.activity.ComponentActivity 5 | import androidx.activity.compose.setContent 6 | import androidx.compose.foundation.layout.* 7 | import androidx.compose.foundation.rememberScrollState 8 | import androidx.compose.foundation.shape.RoundedCornerShape 9 | import androidx.compose.foundation.text.KeyboardOptions 10 | import androidx.compose.foundation.verticalScroll 11 | import androidx.compose.material.* 12 | import androidx.compose.runtime.* 13 | import androidx.compose.ui.Alignment 14 | import androidx.compose.ui.Modifier 15 | import androidx.compose.ui.draw.rotate 16 | import androidx.compose.ui.graphics.Color 17 | import androidx.compose.ui.text.input.KeyboardType 18 | import androidx.compose.ui.tooling.preview.Preview 19 | import androidx.compose.ui.unit.dp 20 | import com.initbase.formvalidator.Form 21 | import com.initbase.formvalidator.FormValidator 22 | import com.initbase.formvalidator.FormValidator.ValidationField 23 | import com.initbase.formvalidator.SnackBarProperties 24 | import com.initbase.formvalidatorlibrary.components.AppButton 25 | import com.initbase.formvalidatorlibrary.components.AppTextField 26 | import com.initbase.formvalidatorlibrary.ui.theme.FormValidatorLibraryTheme 27 | 28 | class MainActivity : ComponentActivity() { 29 | 30 | @ExperimentalMaterialApi 31 | override fun onCreate(savedInstanceState: Bundle?) { 32 | super.onCreate(savedInstanceState) 33 | setContent { 34 | Content() 35 | } 36 | } 37 | 38 | var formTypes = listOf("Regular Form", "Snackbar Form") 39 | 40 | @ExperimentalMaterialApi 41 | @Preview 42 | @Composable 43 | private fun Content() { 44 | FormValidatorLibraryTheme { 45 | // A surface container using the 'background' color from the theme 46 | Surface(color = MaterialTheme.colors.background) { 47 | Column(modifier = Modifier.fillMaxSize()) { 48 | var activeForm by remember { mutableStateOf(0) } 49 | Row( 50 | modifier = Modifier 51 | .fillMaxWidth() 52 | .padding(12.dp) 53 | ) { 54 | formTypes.forEachIndexed { index, s -> 55 | AppButton( 56 | text = s, 57 | modifier = Modifier.weight(1f), 58 | background = if (activeForm == index) MaterialTheme.colors.primary else Color.Gray 59 | ) { 60 | activeForm = index 61 | } 62 | if (index == 0) 63 | Spacer(modifier = Modifier.width(8.dp)) 64 | } 65 | } 66 | if (activeForm == 0) 67 | RegularForm() 68 | else 69 | SnackBarForm() 70 | } 71 | } 72 | } 73 | } 74 | 75 | @ExperimentalMaterialApi 76 | @Composable 77 | private fun SnackBarForm() { 78 | var formIsValid by remember { mutableStateOf(false) } 79 | var name by remember { mutableStateOf("") } 80 | var age by remember { mutableStateOf("") } 81 | var email by remember { mutableStateOf("") } 82 | val nameField = "Name" 83 | val ageField = "Age" 84 | val emailField = "Email" 85 | var activeFlow by remember { mutableStateOf(FormValidator.Flow.Down) } 86 | val validator = FormValidator( 87 | flow = activeFlow, 88 | fields = listOf( 89 | ValidationField( 90 | value = name, 91 | name = nameField, 92 | ), 93 | ValidationField( 94 | value = age.toIntOrNull(), 95 | name = ageField, type = FormValidator.Type.Custom { 96 | (it != null && it % 2 == 0) to "Age must be divisible by two" 97 | } 98 | ), 99 | ValidationField( 100 | value = email, type = FormValidator.Type.Email 101 | ) 102 | ) 103 | ) 104 | Form( 105 | modifier = Modifier 106 | .fillMaxSize() 107 | .verticalScroll(state = rememberScrollState()) 108 | .padding(16.dp), 109 | validator = validator, 110 | snackBarProperties = SnackBarProperties(backgroundColor = Color.Gray.copy(alpha = 0.8f)), 111 | ) { 112 | Text( 113 | text = "Flow", 114 | modifier = Modifier 115 | .align(Alignment.CenterHorizontally) 116 | .padding(bottom = 8.dp), 117 | style = MaterialTheme.typography.subtitle1 118 | ) 119 | Row( 120 | modifier = Modifier.fillMaxWidth(), 121 | verticalAlignment = Alignment.CenterVertically, 122 | horizontalArrangement = Arrangement.Center 123 | ) { 124 | (0..2).forEachIndexed { index, i -> 125 | val active: Boolean 126 | val text = when (index) { 127 | 0 -> { 128 | active = activeFlow == FormValidator.Flow.Down 129 | "Down" 130 | } 131 | 1 -> { 132 | active = activeFlow == FormValidator.Flow.Up 133 | "Up" 134 | } 135 | else -> { 136 | active = activeFlow == FormValidator.Flow.Splash 137 | "Splash" 138 | } 139 | } 140 | Surface( 141 | onClick = { 142 | activeFlow = when (index) { 143 | 0 -> FormValidator.Flow.Down 144 | 1 -> FormValidator.Flow.Up 145 | else -> FormValidator.Flow.Splash 146 | } 147 | }, 148 | color = if (active) MaterialTheme.colors.primary else Color.LightGray, 149 | shape = MaterialTheme.shapes.small, 150 | ) { 151 | Text( 152 | text = text, 153 | modifier = Modifier.padding(vertical = 4.dp, horizontal = 8.dp) 154 | ) 155 | } 156 | if (index != 2) { 157 | Divider( 158 | modifier = Modifier 159 | .padding(horizontal = 2.dp) 160 | .width(16.dp) 161 | .rotate(90f) 162 | ) 163 | } 164 | } 165 | } 166 | Spacer(modifier = Modifier.height(30.dp)) 167 | AppTextField( 168 | label = nameField, 169 | value = name, 170 | placeholder = "Enter name", 171 | onValueChanged = { name = it }, 172 | ) 173 | FormVerticalSpace() 174 | AppTextField( 175 | label = ageField, 176 | value = age, 177 | placeholder = "Enter age", 178 | onValueChanged = { age = it }, 179 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) 180 | ) 181 | FormVerticalSpace() 182 | AppTextField( 183 | label = emailField, 184 | value = email, 185 | placeholder = "Enter email", 186 | onValueChanged = { email = it }, 187 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) 188 | ) 189 | Spacer(modifier = Modifier.height(40.dp)) 190 | AppButton(text = "Submit") { 191 | formIsValid = validator.validate() 192 | } 193 | Spacer(modifier = Modifier.height(40.dp)) 194 | Card( 195 | modifier = Modifier.align(Alignment.CenterHorizontally), 196 | shape = RoundedCornerShape(6.dp), 197 | backgroundColor = if (formIsValid) Color.Green else MaterialTheme.colors.error, 198 | elevation = 0.dp 199 | ) { 200 | Text( 201 | text = if (formIsValid) "Form is valid" else "Form is not valid", 202 | modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) 203 | ) 204 | } 205 | } 206 | } 207 | 208 | @ExperimentalMaterialApi 209 | @Composable 210 | private fun RegularForm() { 211 | var formIsValid by remember { mutableStateOf(false) } 212 | var name by remember { mutableStateOf("") } 213 | var nameError by remember { mutableStateOf(null) } 214 | var age by remember { mutableStateOf("") } 215 | var email by remember { mutableStateOf("") } 216 | var ageError by remember { mutableStateOf(null) } 217 | var emailError by remember { mutableStateOf(null) } 218 | var formError by remember { mutableStateOf(null) } 219 | val nameField = "Name" 220 | val ageField = "Age" 221 | val emailField = "Email" 222 | var activeFlow by remember { mutableStateOf(FormValidator.Flow.Down) } 223 | val validator = FormValidator( 224 | flow = activeFlow, 225 | fields = listOf( 226 | ValidationField( 227 | value = name, 228 | name = nameField, 229 | onError = { 230 | nameError = it 231 | }), 232 | ValidationField( 233 | value = age.toIntOrNull(), 234 | name = ageField, 235 | onError = { 236 | ageError = it 237 | }, type = FormValidator.Type.Custom { 238 | (it != null && it % 2 == 0) to "Age must be divisible by two" 239 | } 240 | ), 241 | ValidationField( 242 | value = email, 243 | onError = { 244 | emailError = it 245 | }, type = FormValidator.Type.Email 246 | ) 247 | ) 248 | ) 249 | Form( 250 | validator = validator, 251 | modifier = Modifier 252 | .fillMaxSize() 253 | .verticalScroll(state = rememberScrollState()) 254 | .padding(16.dp) 255 | ) { 256 | Text( 257 | text = "Flow", 258 | modifier = Modifier 259 | .align(Alignment.CenterHorizontally) 260 | .padding(bottom = 8.dp), 261 | style = MaterialTheme.typography.subtitle1 262 | ) 263 | Row( 264 | modifier = Modifier.fillMaxWidth(), 265 | verticalAlignment = Alignment.CenterVertically, 266 | horizontalArrangement = Arrangement.Center 267 | ) { 268 | (0..2).forEachIndexed { index, i -> 269 | val active: Boolean 270 | val text = when (index) { 271 | 0 -> { 272 | active = activeFlow == FormValidator.Flow.Down 273 | "Down" 274 | } 275 | 1 -> { 276 | active = activeFlow == FormValidator.Flow.Up 277 | "Up" 278 | } 279 | else -> { 280 | active = activeFlow == FormValidator.Flow.Splash 281 | "Splash" 282 | } 283 | } 284 | Surface( 285 | onClick = { 286 | activeFlow = when (index) { 287 | 0 -> FormValidator.Flow.Down 288 | 1 -> FormValidator.Flow.Up 289 | else -> FormValidator.Flow.Splash 290 | } 291 | }, 292 | color = if (active) MaterialTheme.colors.primary else Color.LightGray, 293 | shape = MaterialTheme.shapes.small, 294 | ) { 295 | Text( 296 | text = text, 297 | modifier = Modifier.padding(vertical = 4.dp, horizontal = 8.dp) 298 | ) 299 | } 300 | if (index != 2) { 301 | Divider( 302 | modifier = Modifier 303 | .padding(horizontal = 2.dp) 304 | .width(16.dp) 305 | .rotate(90f) 306 | ) 307 | } 308 | } 309 | } 310 | Spacer(modifier = Modifier.height(30.dp)) 311 | AppTextField( 312 | label = nameField, 313 | value = name, 314 | placeholder = "Enter name", 315 | onValueChanged = { name = it }, 316 | errorMessage = nameError 317 | ) 318 | FormVerticalSpace() 319 | AppTextField( 320 | label = ageField, 321 | value = age, 322 | placeholder = "Enter age", 323 | onValueChanged = { age = it }, 324 | errorMessage = ageError, 325 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) 326 | ) 327 | FormVerticalSpace() 328 | AppTextField( 329 | label = emailField, 330 | value = email, 331 | placeholder = "Enter email", 332 | onValueChanged = { email = it }, 333 | errorMessage = emailError, 334 | keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) 335 | ) 336 | Spacer(modifier = Modifier.height(40.dp)) 337 | AppButton(text = "Submit") { 338 | formIsValid = validator.validate() 339 | formError = validator.errorMessage 340 | } 341 | Spacer(modifier = Modifier.height(40.dp)) 342 | Card( 343 | modifier = Modifier.align(Alignment.CenterHorizontally), 344 | shape = RoundedCornerShape(6.dp), 345 | backgroundColor = if (formIsValid) Color.Green else MaterialTheme.colors.error, 346 | elevation = 0.dp 347 | ) { 348 | Text( 349 | text = if (formIsValid) "Form is valid" else "Form is not valid", 350 | modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) 351 | ) 352 | } 353 | if (formError != null) 354 | Text( 355 | text = formError!!, 356 | modifier = Modifier 357 | .padding(6.dp) 358 | .align(Alignment.CenterHorizontally) 359 | ) 360 | } 361 | } 362 | 363 | @Composable 364 | fun FormVerticalSpace() { 365 | Spacer(modifier = Modifier.height(16.dp)) 366 | } 367 | } -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/ui/components/FormComponents.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary.components 2 | 3 | import androidx.compose.animation.animateContentSize 4 | import androidx.compose.foundation.background 5 | import androidx.compose.foundation.interaction.MutableInteractionSource 6 | import androidx.compose.foundation.layout.* 7 | import androidx.compose.foundation.text.KeyboardActions 8 | import androidx.compose.foundation.text.KeyboardOptions 9 | import androidx.compose.material.* 10 | import androidx.compose.runtime.* 11 | import androidx.compose.ui.Modifier 12 | import androidx.compose.ui.graphics.Color 13 | import androidx.compose.ui.text.TextStyle 14 | import androidx.compose.ui.text.font.FontWeight 15 | import androidx.compose.ui.text.input.VisualTransformation 16 | import androidx.compose.ui.tooling.preview.Preview 17 | import androidx.compose.ui.unit.dp 18 | import androidx.compose.ui.unit.sp 19 | 20 | @Composable 21 | fun AppTextField( 22 | modifier: Modifier = Modifier, 23 | value: String = "", 24 | onValueChanged: (String) -> Unit = {}, 25 | enabled: Boolean = true, 26 | readOnly: Boolean = false, 27 | textStyle: TextStyle = LocalTextStyle.current, 28 | label: String = "Label", 29 | placeholder: String? = null, 30 | errorMessage: String? = null, 31 | keyboardOptions:KeyboardOptions = KeyboardOptions.Default 32 | ) { 33 | Column( 34 | modifier = modifier 35 | .fillMaxWidth() 36 | .background(color = Color.White, shape = MaterialTheme.shapes.small) 37 | .animateContentSize() 38 | ) { 39 | Text( 40 | text = label, 41 | fontSize = 12.sp, 42 | color = MaterialTheme.colors.primary, 43 | fontWeight = FontWeight.W600, 44 | ) 45 | TextField( 46 | enabled = enabled, 47 | readOnly = readOnly, 48 | value = value, 49 | onValueChange = onValueChanged, 50 | modifier = Modifier 51 | .padding(top = 4.dp) 52 | .fillMaxWidth(), 53 | textStyle = textStyle, 54 | visualTransformation = VisualTransformation.None, 55 | keyboardOptions = keyboardOptions, 56 | keyboardActions = KeyboardActions.Default, 57 | singleLine = true, 58 | maxLines = Int.MAX_VALUE, 59 | interactionSource = remember { MutableInteractionSource() }, 60 | placeholder = { 61 | if (placeholder != null) 62 | Text(text = placeholder) 63 | } 64 | ) 65 | if (errorMessage != null) { 66 | Text( 67 | text = errorMessage, 68 | color = MaterialTheme.colors.error, 69 | style = MaterialTheme.typography.caption, 70 | ) 71 | } 72 | } 73 | } 74 | 75 | @Composable 76 | fun AppCheckBox( 77 | modifier: Modifier = Modifier, 78 | value: Boolean, 79 | onCheckedChange: (Boolean) -> Unit, 80 | enabled: Boolean = true 81 | ) { 82 | Checkbox( 83 | checked = value, 84 | onCheckedChange = onCheckedChange, 85 | modifier = modifier.size(30.dp), 86 | enabled = enabled 87 | ) 88 | } 89 | 90 | @Preview 91 | @Composable 92 | fun AppButton( 93 | modifier: Modifier = Modifier, 94 | text: String = "Text", 95 | background:Color=MaterialTheme.colors.primary, 96 | onClick: () -> Unit = {} 97 | ) { 98 | Button( 99 | onClick = onClick, 100 | modifier = modifier 101 | .height(46.dp) 102 | .fillMaxWidth(), 103 | colors = ButtonDefaults.buttonColors( 104 | backgroundColor = background 105 | ) 106 | ) { 107 | Text(text) 108 | } 109 | } -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/ui/theme/Color.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary.ui.theme 2 | 3 | import androidx.compose.ui.graphics.Color 4 | 5 | val Purple200 = Color(0xFFBB86FC) 6 | val Purple500 = Color(0xFF6200EE) 7 | val Purple700 = Color(0xFF3700B3) 8 | val Teal200 = Color(0xFF03DAC5) -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/ui/theme/Shape.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary.ui.theme 2 | 3 | import androidx.compose.foundation.shape.RoundedCornerShape 4 | import androidx.compose.material.Shapes 5 | import androidx.compose.ui.unit.dp 6 | 7 | val Shapes = Shapes( 8 | small = RoundedCornerShape(4.dp), 9 | medium = RoundedCornerShape(4.dp), 10 | large = RoundedCornerShape(0.dp) 11 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/ui/theme/Theme.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary.ui.theme 2 | 3 | import androidx.compose.foundation.isSystemInDarkTheme 4 | import androidx.compose.material.MaterialTheme 5 | import androidx.compose.material.darkColors 6 | import androidx.compose.material.lightColors 7 | import androidx.compose.runtime.Composable 8 | 9 | private val DarkColorPalette = darkColors( 10 | primary = Purple200, 11 | primaryVariant = Purple700, 12 | secondary = Teal200 13 | ) 14 | 15 | private val LightColorPalette = lightColors( 16 | primary = Purple500, 17 | primaryVariant = Purple700, 18 | secondary = Teal200 19 | 20 | /* Other default colors to override 21 | background = Color.White, 22 | surface = Color.White, 23 | onPrimary = Color.White, 24 | onSecondary = Color.Black, 25 | onBackground = Color.Black, 26 | onSurface = Color.Black, 27 | */ 28 | ) 29 | 30 | @Composable 31 | fun FormValidatorLibraryTheme( 32 | darkTheme: Boolean = isSystemInDarkTheme(), 33 | content: @Composable() () -> Unit 34 | ) { 35 | val colors = if (darkTheme) { 36 | DarkColorPalette 37 | } else { 38 | LightColorPalette 39 | } 40 | 41 | MaterialTheme( 42 | colors = colors, 43 | typography = Typography, 44 | shapes = Shapes, 45 | content = content 46 | ) 47 | } -------------------------------------------------------------------------------- /app/src/main/java/com/initbase/formvalidatorlibrary/ui/theme/Type.kt: -------------------------------------------------------------------------------- 1 | package com.initbase.formvalidatorlibrary.ui.theme 2 | 3 | import androidx.compose.material.Typography 4 | import androidx.compose.ui.text.TextStyle 5 | import androidx.compose.ui.text.font.FontFamily 6 | import androidx.compose.ui.text.font.FontWeight 7 | import androidx.compose.ui.unit.sp 8 | 9 | // Set of Material typography styles to start with 10 | val Typography = Typography( 11 | body1 = TextStyle( 12 | fontFamily = FontFamily.Default, 13 | fontWeight = FontWeight.Normal, 14 | fontSize = 16.sp 15 | ) 16 | /* Other default text styles to override 17 | button = TextStyle( 18 | fontFamily = FontFamily.Default, 19 | fontWeight = FontWeight.W500, 20 | fontSize = 14.sp 21 | ), 22 | caption = TextStyle( 23 | fontFamily = FontFamily.Default, 24 | fontWeight = FontWeight.Normal, 25 | fontSize = 12.sp 26 | ) 27 | */ 28 | ) -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/funyin/FormValidator/ca9ff4429f70fd24dbbe2efd975a1355c0eca6fc/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | FormValidatorLibrary 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | 17 | 21 | 22 |