我正在使用 RxSwift
pod 'RxSwift', '~> 4.0'
pod 'RxCocoa', '~> 4.0'
我看到了用户名、密码验证的例子,它的工作原理是这样的
func validateUsername(_ username: String) -> Observable<ValidationResult> {
if username.isEmpty {
return .just(.empty)
}
// this obviously won't be
if username.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
return .just(.failed(message: "Username can only contain numbers or digits"))
}
// this obviously won't be
if username.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
return .just(.failed(message: "Username can only contain numbers or digits"))
}
let loadingValue = ValidationResult.validating
return API
.usernameAvailable(username)
.map { available in
if available {
return .ok(message: "Username available")
}
else {
return .failed(message: "Username already taken")
}
}
.startWith(loadingValue)
}
现在,我需要为电子邮件制作验证器,我没有在示例中找到任何内容如何做?
我以前用Validator https://github.com/SwiftValidatorCommunity/SwiftValidator
validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])
但是在 Rx 中,我完全不知道如何修复它?
谢谢。
最佳答案
final class EmailValidator {
func validate(_ input: String) -> Bool {
guard
let regex = try? NSRegularExpression(
pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}",
options: [.caseInsensitive]
)
else {
assertionFailure("Regex not valid")
return false
}
let regexFirstMatch = regex
.firstMatch(
in: input,
options: [],
range: NSRange(location: 0, length: input.count)
)
return regexFirstMatch != nil
}
}
示例用法:
let emailTextField = UITextField()
let emailValidator = EmailValidator()
emailTextField.rx.text
.orEmpty
.map(emailValidator.validate)
.subscribe(onNext: { isValid in
print(isValid)
})
.disposed(by: disposeBag)
关于swift - 电子邮件验证器 RxSwift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50318186/