Costello Costello - 1 year ago 86
Swift Question

Form validation in reactive cocoa

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

let validUserNameSignal =
.map({ $0.characters.count > 3 })

let pwdPasswordFieldSignal =
.map({$0.characters.count > 3})

let formValidation = validUserNameSignal.combineLatest(with: pwdPasswordFieldSignal)

formValidation.observeValues { (userNameResult,pwdResult) in

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

Answer Source

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
            .map { $0.characters.count > 3 }

    override func 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 {