Swift文本字段和值验证

时间:2017-06-24 02:01:14

标签: swift uitextfield

这看起来很简单,但我无法找到搜索网络的解决方案。我有以下需要验证的变量。如果验证不正确,那么我希望应用停止并返回故事板。

  let mortgageTerm = Double(mortgageTermLabel.text!)
  let name 
  let mtgCashback = Double(casbackRecieved.text!)
  let mtgBalance = Double(mortgageBalance.text!)
  let rate = Double(currentRate.text!)
  • 抵押贷款期限必须大于6且小于或等于60

  • 抵押贷款余额需要大于10,000

  • 费率应大于1但小于10

必须为控件@IBOutlet weak var lenderName: UITextField!选择一个值 - 我是一个客户选择器,为用户提供选择选项。

1 个答案:

答案 0 :(得分:0)

您可以使用guard let这是一个示例

guard let mortgage = Double(mortgageTermLabel.text!) , mortgage > 6 && mortgage <= 60 else {return}

此外,您可以在返回之前以这种方式显示友好的警报消息

guard let mortgage = Double(mortgageTermLabel.text!) , mortgage > 6 && mortgage <= 60 else {
    let alert = UIAlertController(title: "blah", message: "blah blah", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

    self.present(alert, animated: true, completion: nil)
    return
}

guard let balance = Double(mortgageBalance.text!) , balance > 10000 else {
    let alert = UIAlertController(title: "blah", message: "blah blah", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

    self.present(alert, animated: true, completion: nil)
    return
}

guard let date = YourDate , date < Date() else {
    let alert = UIAlertController(title: "blah", message: "blah blah", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

    self.present(alert, animated: true, completion: nil)
    return
}