1

I am trying to validate a form which has multiple textfields. But I can observe only when both textfields are edited...

let validUserNameSignal =
    self.nameTextField
        .reactive
        .continuousTextValues
        .skipNil()
        .map({ $0.characters.count > 3 })

let pwdPasswordFieldSignal = 
    self.lastnameTextField.reactive
        .continuousTextValues
        .skipNil()
        .map({$0.characters.count > 3})

let formValidation =  validUserNameSignal.combineLatest(with: pwdPasswordFieldSignal)

formValidation.observeValues { (userNameResult,pwdResult) in
    print(userNameResult)
    print(pwdResult)
}

Is the way I am doing ok or there is another way?

Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64

2 Answers2

1

Here's an example implementation of a basic ViewController, I've cleaned up a few of the things that I think could be done better.

class ViewController: UIViewController {
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    func nameValidation(for field: UITextField) -> Signal<Bool, NoError> {
        return field
            .reactive
            .continuousTextValues
            .skipNil()
            .map { $0.characters.count > 3 }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let validUserNameSignal = nameValidation(for: nameTextField)
        let lastNameFieldSignal = nameValidation(for: lastNameTextField)
        let formValidation =
            SignalProducer(signal: validUserNameSignal.combineLatest(with: lastNameFieldSignal))
                .map { $0 && $1 }
                .prefix(value: false)

        formValidation.startWithValues {
            print($0)
        }
    }
}
Charles Maria
  • 2,165
  • 15
  • 15
  • [Charlotte Tortorella](http://stackoverflow.com/users/1767606/charlotte-tortorella): NoError is not valid, or I need to import some extra module? – Ignacio Gómez Feb 25 '17 at 21:04
  • I found the answer :D http://stackoverflow.com/questions/35205550/getting-use-of-undeclared-type-noerror-with-reactivecocoa thanks anyway! – Ignacio Gómez Feb 25 '17 at 21:16
0

continuousTextValues is a Signal, which has a hot semantic. This means it emits only changes happened after the observation is made.

You might want to turn your formValidation signal into a producer, and prefix a default value.

SignalProducer(signal: formValidation)
    .map { $0 && $1 }
    .prefix(value: false)
    .startWithValues { ... }
Anders
  • 690
  • 6
  • 7
  • 1
    This code doesn't compile since `formValidation` is a `Signal` of `(Bool, Bool)`. – Charles Maria Nov 28 '16 at 22:46
  • @andres Your hot signal definition is probably wrong –  Nov 29 '16 at 02:50
  • It is true that I've overlooked `formValidation`'s type. I have corrected it. But there is nothing wrong about `continuousTextValues` being a hot signal. – Anders Nov 29 '16 at 15:18