使用0和空文本字段在swift中对Textfields进行验证

时间:2017-10-30 06:08:13

标签: ios swift validation uitextfield

如何验证值大于0的Textfields。我尝试了堆栈溢出的所有建议我没有验证它。以及如何检查textfield的值小于或等于我的标签值。

 let inputStr = totalAmountTextfield.text as? String 
    let inputInt = Int(inputStr!)

    if (inputInt)! < 0 
   {
     let alert = UIAlertView() alert.title = "Message" 
    alert.message = "Enter Valid Amount" 
    alert.addButton(withTitle: "Ok") 
    alert.delegate = self alert.show() }
    else{ print("pay pressed")
     razorpay.open(options) } 
    } 

1 个答案:

答案 0 :(得分:0)

将输入字符串简单转换为double并检查

enter image description here

   class ViewController: UIViewController {


        @IBOutlet weak var txt: UITextField!

        @IBAction func onClickSubmit(_ sender: Any)
        {
            let inputStr:String = txt.text ?? ""

            let alert = UIAlertController()
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))

            if inputStr.isEmpty
            {
                alert.message = "Please Enter Text"
                self.present(alert, animated: true, completion: nil)

            }
            else
            {
                let inputInt = inputStr.integerValue

                if (inputInt)! < 0
                {
                    alert.message = "Enter Valid amount"
                       self.present(alert, animated: true, completion: nil)

                }

                else
                {
                    print("Pay to Proceed")
                }
            }

        }

    }

    extension String
    {

        func isNumber() -> Bool{
            let numberCharacters = CharacterSet.decimalDigits.inverted
            return !self.isEmpty && self.rangeOfCharacter(from:numberCharacters) == nil
        }
        struct NumberFormat
        {
            static let instance = NumberFormatter()
        }
        var integerValue:Int?
        {
            if self.isEmpty
            {
                return 0
            }
            else
            {
                return (NumberFormat.instance.number(from: self)?.intValue) ?? 0
            }
        }
    }