Reputation:
I want multiple validation for VIN Number UITextField in Swift
It should be Capital letters only
It can contain 0-9 Numbers
No spaces and special characters allowed
Total length must be 16 characters
Upvotes: 0
Views: 779
Reputation: 82759
For Swift 3.0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.characters.count == 0 {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)
return prospectiveText.containsOnlyCharactersIn(matchCharacters: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&
prospectiveText.characters.count <= 16
}
extension String {
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {
let disallowedCharacterSet = NSCharacterSet(charactersIn: matchCharacters).inverted
return self.rangeOfCharacter(from: disallowedCharacterSet) == nil
}
}
Upvotes: 3
Reputation: 4065
The best solution is regular expression!
Simple as that [A-Z0-9]{16}
.
NSString *testString=@"ABSDF9DFDSFPOIS1";
NSString *regExPattern = @"[A-Z0-9]{16}";
NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:testString options:0 range:NSMakeRange(0, [testString length])];
if (regExMatches==0) {
//Not matched
}
Take a look here to see how this regex works and you will realise how flexible is to change.
Upvotes: 1
Reputation: 2220
You can achieve all validation as following for Objective-C
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==YOUR_USER_NAME_TEXTFIELD || textField == YOUR_PASSWORD_TEXTFIELD)
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
return NO;
}
}
return YES;
}
return YES;
}
for Total length must be 16 characters
You can count the length of yourtextfield.
Upvotes: 0