Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save samirthebti/73c0e1b69620dd1df8c7c9bf4f391534 to your computer and use it in GitHub Desktop.
Save samirthebti/73c0e1b69620dd1df8c7c9bf4f391534 to your computer and use it in GitHub Desktop.
RxSwift - Validation sample
import UIKit
import RxSwift
import RxCocoa
let requiredUserNameLength = 5
let requiredPasswordLength = 5
let limitUserNameLength = 20
class ValidationViewController: UIViewController {
@IBOutlet weak var userNameText: UITextField!
@IBOutlet weak var userNameRemainLabel: UILabel!
@IBOutlet weak var userNameValidationLabel: UILabel!
@IBOutlet weak var passwordText: UITextField!
@IBOutlet weak var passwordInvalidLabel: UILabel!
@IBOutlet weak var loginButton: UIButton!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let userNameValid: Observable<Bool> = userNameText.rx_text
.map{ text -> Bool in
text.characters.count >= requiredUserNameLength
}
.shareReplay(1)
let userNameRemainText: Observable<String> = userNameText.rx_text
.map { text -> String in
let currentLength = text.characters.count
return "\(currentLength)/\(limitUserNameLength)"
}
let passwordValid: Observable<Bool> = passwordText.rx_text
.map { text -> Bool in
text.characters.count >= requiredPasswordLength
}
.shareReplay(1)
let everythingValid: Observable<Bool>
= Observable.combineLatest(userNameValid, passwordValid) { $0 && $1 }
userNameValid
.bindTo(userNameValidationLabel.rx_hidden)
.addDisposableTo(disposeBag)
userNameRemainText
.bindTo(userNameRemainLabel.rx_text)
.addDisposableTo(disposeBag)
passwordValid
.bindTo(passwordInvalidLabel.rx_hidden)
.addDisposableTo(disposeBag)
everythingValid
.bindTo(loginButton.rx_enabled)
.addDisposableTo(disposeBag)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment