Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate NSString for Hexadecimal value

Tags:

cocoa

nsstring

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 ?

like image 702
MatterGoal Avatar asked Nov 04 '11 15:11

MatterGoal


4 Answers

Swift 5

extension String {
    var isHexNumber: Bool {
        filter(\.isHexDigit).count == count
    }
}

print("text1".isHexNumber) // false
print("aa32".isHexNumber) // true
print("AD1".isHexNumber) // true
like image 75
pawello2222 Avatar answered Nov 15 '22 22:11

pawello2222


Does this method work for you?

    NSString *string = @"FF";

    NSCharacterSet *chars = [[NSCharacterSet 
        characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet];

    BOOL isValid = (NSNotFound == [string rangeOfCharacterFromSet:chars].location);
like image 33
Francis McGrew Avatar answered Nov 16 '22 00:11

Francis McGrew


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
}
like image 5
Ole Begemann Avatar answered Nov 16 '22 00:11

Ole Begemann


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
  }

}
like image 3
Luca Davanzo Avatar answered Nov 15 '22 23:11

Luca Davanzo