ios - Swift - 如何将 SwiftValidator 集成到我的项目中

标签 ios forms swift validation

我有一个登录表单,它有两种替代形式,具体取决于用户点击分段控件的方式....或者作为带有电子邮件、密码和重复密码的注册表单;或仅包含电子邮件和密码的登录表单。

当用户填写注册或登录字段并点击注册/登录按钮时......我使用代码让用户登录......

    @IBAction func loginRegisterTapped(sender: AnyObject) {
       //check whether the sender tag is registerTag (in which case a new user is registering or alternately returning user logging in 
       //do various checks and if all good submit the form
}

我最近将一个验证库 (SwiftValidator) 复制到我的项目中,并将其配置为在点击登录/注册按钮时也验证字段,即我在 loginRegisterTapped ibaction 方法中将验证代码插入到我自己的代码之上。集成 SwiftValidator 后我的代码本质上变成了

@IBAction func loginRegisterTapped(sender: AnyObject) {
       //validation
    self.clearErrors()
    validator.validate(self)
       //check whether the sender tag is registerTag (in which case a new user is registering or alternately returning user logging in 
       //do various checks and if all good submit the form
}

SwiftValidator 库结束了我们在验证成功或失败时调用 2 个委托(delegate)方法(在我的 LoginViewController 中)

    // SwiftValidator library Delegate methods
func validationSuccessful() {
    // submit the form
}
func validationFailed(errors:[UITextField:ValidationError]) {
    // turn the fields to red
    for (field, error) in validator.errors {
        field.layer.borderColor = UIColor.redColor().CGColor
        field.layer.borderWidth = 1.0
        error.errorLabel?.text = error.errorMessage // works if you added labels
        error.errorLabel?.hidden = false
    }
}

如果验证成功,我如何获取代码以返回我的@IBAction func loginRegisterTapped(sender: AnyObject) 方法并继续我自己的表单提交代码(...我需要对发件人的引用以检查它的标签确定按钮是被点击为“注册”按钮还是“登录”按钮),而不是按照 SwiftValidator 库的建议在它的 validationSuccessful 委托(delegate)方法中进行表单提交,我无权访问发件人变量。即我在这里有什么选择或者什么被认为是最佳实践? ...我考虑过自定义 validationSuccessful 方法以向调用函数返回一个 bool 值,但怀疑这是否是最好的方法?

最佳答案

恕我直言,我会在 validationSuccessful() 方法中成功提交表单,而不是在您自己的操作方法中。我会避免使用标签来区分登录和注册按钮,而是让每个按钮都调用一个单独的操作方法。通过使用相同的处理程序处理它们,您不会节省任何时间、代码或逻辑清晰度。

关于ios - Swift - 如何将 SwiftValidator 集成到我的项目中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172619/

相关文章:

ios - 使用企业分发在 iOS 8 和 iOS 9 上推送通知

ios - aws dynamodb 如何在 ios 中使用对象映射器和批处理获取

php - Symfony表单未显示正确的错误(正在星座图上)

javascript - 选择循环创建的文本输入框中写入的值

ios - 向 Swift 2 中的类添加 'for...in' 支持

ios - UICollectionView moveItemAtIndexPath :toIndexPath: issues moving items not on screen

ios - 在项目之间复制 View Controller

c# - 使用 try/catch 作为测试的错误形式?

ios - Swift 在闭包中传入变量

ios - UITableViewAutomaticDimension 单元格在滚动或拉动刷新后调整大小