简体   繁体   English

使用RxSwift和RXCocoa验证按钮单击时的所有文本字段

[英]Validate all textfield on button click using RxSwift and RXCocoa

I am new to RxSwift and RxCocoa and I'm learning it. 我是RxSwift和RxCocoa的新手,正在学习中。

I want to validate all textfield on button click and based on the validation I need to show alert message to user. 我想在按钮单击时验证所有文本字段,并基于验证,我需要向用户显示警报消息。

After validation is successful I need to insert record in table. 验证成功后,我需要在表中插入记录。

Refer the following code... 请参考以下代码...

var result = txtFname.rx.text
    result.asObservable().subscribe(onNext: { text in
        if text!.isEmpty {
            self.showAlert(msg: "Plese enter first name.")
            self.txtFname.becomeFirstResponder()
        }
    }).disposed(by: disposeBag)

    result = txtLname.rx.text
    result.asObservable().subscribe(onNext: { text in
        if text!.isEmpty {
            self.showAlert(msg: "Please enter last name.")
            self.txtLname.becomeFirstResponder()
        }
    }).disposed(by: disposeBag)

    result = txtEmail.rx.text
    result.asObservable().subscribe(onNext: { text in

        if text!.isEmpty {
            self.showAlert(msg: "Please enter email id.")
            self.txtLname.becomeFirstResponder()
        }
    }).disposed(by: disposeBag)

   //need to check here if all fields are valid or not 
   //if all fields are valid then insert record....

When I press a button and it check all the validation at one and show alert... 当我按下一个按钮时,它一次检查所有验证并显示警报...

But I want to do like if one validation is fail then it should not go further until previous validation is successful... 但是我想做的是,如果一个验证失败,那么在先前的验证成功之前,它不应该继续下去...

I don't know how to achieve this. 我不知道该如何实现。 Any help will be appreciated. 任何帮助将不胜感激。

You could do something like this. 你可以做这样的事情。

  self.button.rx.tap.asObservable()
     .filter({ (_) -> Bool in
        guard !(self.txtFname.text ?? "").isEmpty else {
           self.showAlert(msg: "Please enter first name.")
           self.txtFname.becomeFirstResponder()
           return false
        }

        guard !(self.txtLname.text ?? "").isEmpty else {
           self.showAlert(msg: "Please enter last name.")
           self.txtLname.becomeFirstResponder()
           return false
        }

        guard !(self.txtEmail.text ?? "").isEmpty else {
           self.showAlert(msg: "Please enter email id.")
           self.txtEmail.becomeFirstResponder()
           return false
        }

        return true
     })
     .subscribe { _ in
        // do something when all the fields are valid
        self.showAlert(msg: "All fields are valid")
     }
     .disposed(by: disposeBag)

It's not exactly the same answer but you can achieve something like this. 答案并不完全相同,但是您可以实现以下目标。

      class DataValidator {
            class func validName(name:String) -> Bool {
            if let regex =
            try? NSRegularExpression(pattern: "^\\w+( \\w+\\.?)*$", options:
            .CaseInsensitive) {
            return name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 2 &&
            regex!.matchesInString(name, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0,
            name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))).count > 0 }
            return false }

            class func validEmail(email:String) -> Bool{ if let regex =
            try? NSRegularExpression(pattern: "^\\S+@\\S+\\.\\S+$", options: .CaseInsensitive){
            return regex!.matchesInString(email, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0,
            email.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))).count > 0 }
        return false }
 }

}// end of validator class

You can use something like below: 您可以使用如下所示的内容:

let nameSignal:RACSignal = nameTextField.rac_textSignal().map { (text) -> AnyObject! in
return DataValidator.validName(text as! String) }
let emailSignal = emailTextField.rac_textSignal().map { (text) -> AnyObject! in
return DataValidator.validEmail(text as! String) }

RACSignal.combineLatest([nameSignal, emailSignal]).subscribeNext { (valid) -> Void in
   self.button.enabled = valid as! Bool
}
class Validator {

    class func validEmail(email:String) -> Bool {
        if let regex = try? NSRegularExpression(pattern: "^\\S+@\\S+\\.\\S+$", options: .caseInsensitive){
        return regex.matches(in: email, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0,                                                                                                                        email.lengthOfBytes(using: String.Encoding.utf8))).count > 0 }
        return false
    }
}

Then you can use it as follows: 然后,您可以按以下方式使用它:

var isValid : Observable<Bool>{
    return Observable.combineLatest(username.asObservable())
    { (username) in
        return Validator.validEmail(email: username)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RxSwift,RxCocoa和UITableview - RxSwift, RxCocoa and UITableview Rxswift ios - 验证 OTP 字段并在按钮单击时确认 OTP 字段 - Rxswift ios - Validate OTP field and Confirm OTP field on button click 基于文本字段输入的 RxSwift 启用/禁用按钮 - RxSwift enable/disable button based on textfield input Swft3(RxSwift,RxCocoa)-使用反应式编程的TableView展开和折叠概念 - Swft3 (RxSwift, RxCocoa) - TableView Expand and collapse concept using reactive programming 使用RxSwift和RxCocoa绑定模型并更新单元格 - Bind model and update cell with RxSwift and RxCocoa 为什么`NotificationCenter + Rx`位于RxCocoa中而不是RxSwift中 - Why `NotificationCenter+Rx` is in RxCocoa not RxSwift 处理UITableView绑定中的连接错误(Moya,RxSwift,RxCocoa) - Handle Connection Error in UITableView Binding (Moya, RxSwift, RxCocoa) 在RxCocoa / RxSwift中,如何观察BehaviorRelay &lt;[object]&gt;数组大小已更改 - In RxCocoa/RxSwift, how to observe BehaviorRelay<[object]> array size changed 如何测试RxSwift变量和RxCocoa Observable之间的UI绑定? - How to test the UI Binding between RxSwift Variable and RxCocoa Observable? 当委托字段不称为`delegate`时实现`DelegateProxy`(RxSwift / RxCocoa) - Implementing `DelegateProxy` (RxSwift/RxCocoa) when delegate field is not called `delegate`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM