我正在尝试验证文本并将其与UITextField键入事件合并。这是验证顺序:
let validation = textField.rx.text.map {ValidationService.validate($0)}
我测试了所有组合方法,但没有结果:
Observable.zip(textField.rx.controlEvent(.editingChanged), validation)
// Select
// No event
// Typing: "A"
// zip failed(message: "Field cannot be empty") () <- wrong
// Typing: "Aa"
// zip failed(message: "Field cannot be empty") () <- wrong
// Typing: "Aaa"
// zip failed(message: "Email is wrong") () <- correct
// UnSelect
// No event
Observable.combineLatest(textField.rx.controlEvent(.editingChanged), validation)
// Select
// No event
// Typing: "A"
// combineLatest combineLatest failed(message: "Email is wrong") () <- correct
// Typing: "Aa"
// combineLatest failed(message: "Field cannot be empty") () <- correct
// combineLatest failed(message: "Field cannot be empty") () <- correct
// UnSelect
// combineLatest failed(message: "Email is wrong") () <- wrong
validation
.withLatestFrom(textField.rx.controlEvent(.editingChanged))
// Select
// No event
// Typing: "A"
// No event
// Typing: "Aa"
// withLatestFrom () failed(message: "Email is wrong") <- correct
// UnSelect
// withLatestFrom () failed(message: "Email is wrong") <- wrong
您知道其他解决我问题的方法吗?
答案 0 :(得分:0)
在您的viewDidLoad()中尝试一下:
textField.rx.text.orEmpty
.map { $0.isValidEmail }
.subscribe(onNext: { isValid in
print("email is \(isValid ? "" : "Not") Valid")
})
以上使用此扩展名:
extension String {
var isValidEmail: Bool {
let emailRegex = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
let predicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return predicate.evaluate(with: self)
}
}