Forked from YusukeHosonuma/ValidationViewController.swift
Created
August 20, 2018 07:36
-
-
Save nhatlee/0e6bfcd7cfa623f41a10f06a67ce9d3b to your computer and use it in GitHub Desktop.
RxSwift - Validation sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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