Allowing pasting of numbers only from an alphanumeric in a textfield - ios

I want the textfield to allow the user to paste only numbers from the alphanumeric text and the same should be displayed.I have already dealt with the keypad part.I have tried the delegate method but it restricts the text altogether ,if it contains any alphabet ,which is not my requirement.
I have gone through the discussions but couldn't find what i was looking for.Suggestions please!!

Try this
Make a macro
#define ACCEPTABLE_CHARECTERS #"0123456789."
And use it
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==textFieldAmount)
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
return YES;
}

Check Your textfield containing only numbers or not by using below code :
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [yourTextFieldText isSupersetOfSet:inStringSet];
if (!valid)
{
// Not numeric
}
else
{
//valid number
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:#""];
textField.text = filtered;
return NO;
}

Related

Objective-C : validating text field with number

I'm new to iOS development. I want to know about how we can validate text field if it contains number with some specific range, say 10 for contact number ? Is there any predefined function available ?
Thank you.
+ (BOOL) validatePassword:(NSString *)passWord
{
NSString *passWordRegex = #"^[a-zA-Z0-9]{6,20}+$";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",passWordRegex];
return [passWordPredicate evaluateWithObject:passWord];
}
To have textfield to accept only numbers and only till 10 digit length you can use this function.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *acceptedCharsters = #"0123456789";
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedCharsters] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
return YES;
}

Regex in iOS to limit a text field to only letters and single apostrophies

After a text field is returned I want to check if the text provided is valid. Valid means only letters or a single apostrophe, for names.
I'm pretty new to regular expressions. Is there a simple regular expression I can use for this check, or can someone point me towards some reading material where I can learn to compose a regular expression that will fit my needs?
You can do it like this, but you need to show an error in case the input is invalid.
- (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
{
NSString *const regularExpression = #"^[a-zA-Z']+$";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
options:kNilOptions
error:&error];
if (error) {
// Handle error
}
NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString
options:0
range:NSMakeRange(0, [aString length])];
return numberOfMatches > 0;
}
The regx should be
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
you can use
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if (textField == emailid) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
;
return [string isEqualToString:filtered];
}
}
You can use the function that checks whether the input should be inserted or not and restrict the characters there. Since your restriction is fairly simple there is no need of regular expressions and you can use characters sets.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters addCharactersInString:#"'"];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}

How to restrict UITextField to a defined set of characters and limit the length?

I am working on a login and resister view controller. I am limiting usernames to 12 characters and passwords to 16 using :
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField==self.userField){
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 12);
}
else if(textField==self.passwordField){
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] > 16);
}
return YES;
}
this works well but I also want to limit it to a set of characters to stop unwanted symbols and also Chinese characters. I want to define this set:
#define ACCEPTABLE_CHARACTERS #"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Not sure how to add it to the method above though and get both working. If I was to check for the character set only and not length the code would be:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
Not sure how to combine them though. Can someone help me please? Thanks!
You can do it like (I divided it to function for more readability and easy to scale the conditions)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return ([self checkLengthOfString:newString inField:textField] && [self checkCharacter:newString]);
}
// Check Length
- (BOOL)checkLengthOfString:(NSString *)text inField:(UITextField *)textField
{
if(textField == self.userField)
{
return !([text length] > 12);
}
else if(textField == self.passwordField)
{
return !([text length] > 16);
}
}
// Check character
- (BOOL)checkCharacter:(NSString *)text
{
BOOL status = YES;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSRange r = [text rangeOfCharacterFromSet:s];
if (r.location != NSNotFound)
{
status = NO;
}
return status;
}
Why don't you just use a regEx to match that chars?
I know this has already been answered, but I had a similar scenario and I found none of the answers on StackOverflow handled the Backspace character.
I needed to limit input into a UITextField to a specific number of AlphaNumeric characters, but be able to enter spaces.
Also, using [textField length] > kMAXNUMCHARS caused a problem: you couldn't backspace once you hit the max number of chars.
So here's my complete solution. It also disallows leading spaces. Trailing spaces are trimmed elsewhere when the value is saved (in my case to a PLIST file)
In my Constants.h file I defined:
#define ALLOWED_CHARECTERS #" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
extern const int kMAXUSERNAMELENGTH;
then in Constants.m:
const int kMAXUSERNAMELENGTH = 9;
I define my class as UITextFieldDelegate with the line
[self._txtUsername.textField setDelegate:self];
Don't forget to declare the UITextFieldDelegate protocol in your class definiion
#interface MyClass : CCNode <UITextFieldDelegate>
And finally,
//UITextFiledDelegate Protocol method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//disallow leading spaces. must allow trailing spaces- never know if we'll add another char
//we trim trailing spaces when we save the TextField value, in our case to Plist file
if (range.location == 0 && [string isEqualToString:#" "])
return NO;
//we use defined ALLOWED_CHARECTERS so we can add chars later, easily.
//we could use [NSCharacterSet alphanumericCharacterSet] if we don't need to allow spaces
NSCharacterSet *allowedInput = [NSCharacterSet characterSetWithCharactersInString:ALLOWED_CHARECTERS];
NSArray* arChar = [string componentsSeparatedByCharactersInSet:allowedInput]; //arChar.count = 1 if 'allowedInput' not in 'string'
//disallow input if its not a backspace (replacementString paramater string equal #"" if a backspace) AND
//(disallow input >= kMAXUSERNAMELENGTH chars, OR disallow if not in allowed allowedChar set
if ( ![string isEqual:#""] && ( [textField.text length] >= kMAXUSERNAMELENGTH || !([arChar count] > 1)) )
return NO;
return YES;
}
I hope this helps someone.

how to validation and format input string to 1234567890 to 123-456-7890

I have to format input string as phone number.For i am using
(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:#""];
if (string.length==3||string.length==7) {
filtered =[filtered stringByAppendingString:#"-"];
}
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
here
#define NUMBERS_ONLY #"1234567890-"
#define CHARACTER_LIMIT 12
but its not editing back.
Please give some ideas
The method you're using is a UITextFieldDelegate method that determines whether or not to allow a change to the text field - given the range and replacement text, should the change be made (YES or NO).
You're trying to format a string while it is being typed - for this you'll also need to update the value of the textField.text property. This could be done in the same method while returning a "NO" afterwards.
For validation,
- (BOOL) isValidPhoneNumber
{
NSString *numberRegex = #"(([+]{1}|[0]{2}){0,1}+[0]{1}){0,1}+[ ]{0,1}+(?:[-( ]{0,1}[0-9]{3}[-) ]{0,1}){0,1}+[ ]{0,1}+[0-9]{2,3}+[0-9- ]{4,8}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",numberRegex];
return [numberTest evaluateWithObject:self.inputString];
}
You can use this for formatting the string,
self.inputString = #"1234567890"
NSArray *stringComponents = [NSArray arrayWithObjects:[self.inputString substringWithRange:NSMakeRange(0, 3)],
[self.inputString substringWithRange:NSMakeRange(3, 3)],
[self.inputString substringWithRange:NSMakeRange(6, [self.inputString length]-6)], nil];
NSString *formattedString = [NSString stringWithFormat:#"%#-%#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];

Restricting the number of characters entered in UiTextfield by user

I am trying to restrict the number of characters entered in UITextfied,I want the user to enter the numbers in range 40.[0 to 9] to 250.[0 to 9] and the user can only one digit after the decimal point and also he cant enter multiple decimal points. I hope I have made my point clear, so far I have tried some code which is below
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
// allow backspace
if (range.length > 0 && [string length] == 0) {
return YES;
}
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:#"."]) {
return NO;
}
// set the text field value manually
NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:#""];
textField.text = newValue;
// return NO because we're manually setting the value
return NO;
}
So friends please help me further.
Regards
Ranjit

Resources