Created
July 11, 2016 05:20
-
-
Save sanketfirodiya/766b5ed6fe4732409e83b8bfe5809ab3 to your computer and use it in GitHub Desktop.
UITextField extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension UITextField { | |
func containsOnlyNumbers(string: String, maximumDecimalPlaces: NSInteger, maximumValue: NSInteger) -> Bool { | |
// Check that textfield only contains allowed number of decimal places (this can also be done in regex, but avoiding so that is easier to understand and debug | |
if string.characters.contains(".") { | |
if string.componentsSeparatedByString(".").count > 2 { | |
return false | |
} else { | |
let newStringSplitAtDecimal = string.componentsSeparatedByString(".") | |
if newStringSplitAtDecimal.count > 1 { | |
let decimalPlaces = newStringSplitAtDecimal.last | |
if decimalPlaces?.characters.count > maximumDecimalPlaces { | |
return false | |
} | |
} | |
} | |
} | |
// Check that textfield only contains numbers and decimal (.) | |
let regularExpression = maximumDecimalPlaces > 0 ? "^[0-9.]*$" : "^[0-9]*$" | |
do { | |
let regex = try NSRegularExpression(pattern: regularExpression, options: .CaseInsensitive) | |
let numberOfMatches = regex.numberOfMatchesInString(string, options: .Anchored, range: NSMakeRange(0, string.characters.count)) | |
if numberOfMatches == 0 { | |
return false | |
} | |
} catch { | |
return false | |
} | |
let stringInt = (string as NSString).integerValue | |
if stringInt > maximumValue { | |
return false | |
} | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment