I want to validate my UITextfield for number of characters less than 2 and only numbers should be entered... seen this
Asked
Active
Viewed 2,322 times
0
-
What do you mean with only characters less than 2? – mfaerevaag Jun 07 '13 at 09:58
-
try the answer posted... – Agent Chocks. Jun 07 '13 at 10:04
5 Answers
6
Try this one...
#define NUMBERS_ONLY @"1234567890"
#define CHARACTER_LIMIT 2
and in this method----
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}

Agent Chocks.
- 1,312
- 8
- 19
1
This works!!
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string isEqualToString:@""]) return YES;
unichar c = [string characterAtIndex:0];
if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:c])
{
int maxVal = 2;
if (textField.text.length >= maxVal)
return NO;
else
return YES;
} else {
return NO;
}
}

Luis Enrique Díaz
- 419
- 3
- 4
0
The standard way of dealing with this in iOS is attaching a UITextFieldDelegate
to your UITextField
, and implement textField:shouldChangeCharactersInRange:replacementString:
method. Inside this method you can validate the string
use property length
to achieve this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if([textField.text length]<2)
return YES;
else
return NO;
}

Lithu T.V
- 19,955
- 12
- 56
- 101
-
Actually the standard in iOS and MacOS X is to use key-value coding validation (https://developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/Validation.html). An example of this is: https://github.com/quellish/KVCValidationExample – quellish Jul 24 '14 at 20:26
0
try like this,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if([textField.text length]<2)
return YES;
else
return NO;
}
and assign NSNumberkeyboard
type to the textfield.
0
Another way to declare a NSCharaterSet
with all letters and check that the field's text does not contain any of them:
NSCharacterSet *alphabet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"]
if ([[self.label.text lowercaseString] rangeOfCharacterFromSet:alphabet].location != NSNotFound)
{
NSLog(@"Found letters!");
}

mfaerevaag
- 730
- 5
- 29