美文网首页
判断textfeild输入纯数字,长度为11

判断textfeild输入纯数字,长度为11

作者: 存在即是美 | 来源:发表于2020-06-23 16:11 被阅读0次
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        //设置该处 , 输入只能是数字和小数点
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        
        let expression = "^[0-9]*([0-9])?$"
    
        let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
        
        let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
    
        if textField.text!.count == 11 {
            if string.isEmpty {
               return true
            }else {
                return false
            }
        }else {
            return numberOfMatches != 0
        }
    
    }
    

    相关文章

      网友评论

          本文标题:判断textfeild输入纯数字,长度为11

          本文链接:https://www.haomeiwen.com/subject/ubyhfktx.html