Giter Club home page Giter Club logo

fieldvalidator's Introduction

FieldValidator

Validate fields, not views

Every Android developer faces with validating user input (email, phone, license agreement etc.). Validating user input means getting this input from View, validating it and then displaying the validation result. Screen validation with more than several Edittexts could be a bit challenging, combining everything listed above for every single view, is not that simple and brings a lot of boilerplate code. FieldValidator is attempt to get rid of coupling user input validation with view and focus mainly on data validation without boilerplate. Although such approach could be useful for MVVM like architecture with Android Databinding usage, it can be used in other architecture patterns and without DataBinding. The library is designed to be used along with Kotlin.

Quick overview

  • Supports simple on demand validation
  • Auto validation, instant validation as field value changes
  • Validation result is delievering directly to views
  • Easy API and Kotlin delegates to simplify initialisation

Installation

Step 1: Add in your root build.gradle of your project

allprojects {
    repositories {
      // ...
      maven { url 'https://jitpack.io' }
    }
  }

Step 2: Add the dependency to your app gradle file

dependencies {
  //...
  implementation 'com.github.skiff2011:fieldvalidator:$latestVersion'
  //...
}

Usage

  1. Condition<T : Any?> class instance is responsible for single field validation. You have to choose condition that suits your nedds or write your own.
open class RegexCondition(
  private val error: String,
  private val regex: Regex
) : Condition<String> {
  override fun validate(value: String): ValidationResult =
    if (value.matches(regex)) Valid else Error(error)
}
  1. ValidationViewState<T : View> is responsible for displaying View`s state depending on validation result. Validation error is represnted by String value. Implement this interface for required view.
class TextInputLayoutViewState : ValidationViewState<TextInputLayout> {
  override fun showError(error: String, view: TextInputLayout) {
    view.error = error
  }

  override fun hideError(view: TextInputLayout) {
    view.error = null
  }
}
  1. Create validator instance in your ViewModel(Presenter, Activity, Fragment etc.)
class YourViewModel() {
   // ...
  val validator = FieldValidator()
   // ...
}
  1. Define your data fields using corresponding delegate provided by library. ViewId is a key for field storing in a map. If you don`t want to display validation state, you can pass any unique Int Id.
class YourViewModel() {
// ...
var string0: String by validator.validateable(
    initialValue = "",
    viewId = R.id.til1,
    condition = EmptyStringCondition(),
    viewState = TextInputLayoutViewState()
  ) { value ->
    // value changed listener if required (optional)
  }
  // ...
}
  1. Subscribe view to validation state changes with a help of @BindingAdapter method provided by the library by passing validator instance as argument. If view state display is not required omit this step (Silent validation).
<?xml version="1.0" encoding="utf-8"?>
<layout>
  // ...
  <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/til1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Some Hint"
        app:errorEnabled="true"
        validator="@{viewModel.validator}"
        >

      <com.google.android.material.textfield.TextInputEditText
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="@={viewModel.string0}"
          />

    </com.google.android.material.textfield.TextInputLayout>
    // ...
</layout>

As you can see two way binding is used to update field value, but it is optional. You can use any suitable way for you, TextWatcher for example.

Alternatively:

import com.skiff2011.fieldvalidator.view.bindValidator

class YourFragment {
  // ...
  val validator = FieldValidator()
  lateinit var til1: TextInputLayout
  // ...
  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
  ): View? {
    // create view
    bindValidator(til1, validator)
  }
  
  // ...
}
  1. Validate validator by calling validator.validate. The returned Boolean value will be the result. You can also pass List<Int> of ids to validate only some fields.
class YourViewModel() {
// ...
  val validator = FieldValidator()
  // ...
  
  fun onValidateButtonClicked() {
    if (validator.validate) {
      // go next
    }
  }
}

You can also use FieldAutoValidator to perform field validation as its value changes. You have to create FieldAutoValidator instance instead of FieldValidator as describen above and pass ValidationCallback instance, which will be called when validator changes its state.

class YourViewModel() {
  // ...
  val validator = FieldAutoValidator(validationCallback = ValidationCallback { value ->
    //validator new status
    if (!value) {
    //disable button
    }
  })
  // ...
}

Then you have to enable auto validation by calling validator.enableAutoValidation(). You can pass List<Int> of ids to enable validation only for some views.

class YourViewModel() {
  // ...
  val validator
  var buttonClickCounter = 0
  // ...
  fun onButtonClicked() {
  //enable autovalidation after the first button click
    if (counter == 0) {
      validator.enableAutoValidation()
    }
  }
}

Sometime it is necessary to include/exclude fields from validation process depending on some conditions. For this purpose you can use validator.enableAutoValidation(listOf(R.id.til1, R.id.til2) and validator.disableAutoValidation(listOf(R.id.til1, R.id.til2) After disabling field autovalidation, View tied to field will return in default state(Valid).

License

Copyright 2019 Oleksii Smovzhenko

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

fieldvalidator's People

Contributors

skiff2011 avatar

Stargazers

Denys Pupin avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.