I'm working on a custom NSFormatter.
I need to verify user input step by step... i thought to check by isPartialStringValid:
if the string contains only permitted chars "0123456789ABCDEF".
How can i verify this condition ? is there a way with NSString function to check if a string contain only some chars ?
extension String {
var isHexNumber: Bool {
filter(\.isHexDigit).count == count
}
}
print("text1".isHexNumber) // false
print("aa32".isHexNumber) // true
print("AD1".isHexNumber) // true
Does this method work for you?
NSString *string = @"FF";
NSCharacterSet *chars = [[NSCharacterSet
characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet];
BOOL isValid = (NSNotFound == [string rangeOfCharacterFromSet:chars].location);
You can create a custom NSCharacterSet
that contains the permitted characters (+ characterSetWithCharactersInString:
) and then test the string against it with rangeOfCharacterFromSet:
. If the returned range is equal to the entire range of the string, you have a match.
Another option would be matching with NSRegularExpression
.
Sample code Swift:
func isValidHexNumber() -> Bool {
guard isEmpty == false else { return false }
let chars = CharacterSet(charactersIn: "0123456789ABCDEF").inverted
return uppercased().rangeOfCharacter(from: chars) == nil
}
In swift 2.1 you can extends String in this way:
extension String {
func isValidHexNumber() -> Bool {
let chars = NSCharacterSet(charactersInString: "0123456789ABCDEF").invertedSet
guard self.uppercaseString.rangeOfCharacterFromSet(chars) != nil else {
return false
}
return true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With