I need to display mobile number in 123-456-7890 in text field. To do that, I am using this code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
if (charCount == 3 || charCount == 7) {
newString = [newString stringByAppendingString:#"-"];
}
textField.text = newString;
return NO;
}
it works fine,but I have a problem,
for example I need to display mobile number 1234567890 like this 123-456-7890.
I entered 123-456, by mistake I enter wrong value then to modify it backspace remove 456 but it is not removed - symbol.
How can I remove it also?
May be not a full solution, but a quick hack that should work - you can always let user delete any character (or substring), so try just put the following condition in the beginning of your method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string length] == 0)
return YES; // deleting is always OK - returning YES
...
I hope we can do it in this way:
NSMutableString *phoneNumber = [NSMutableString stringWithFormat:#"%#", textField.text];
[phoneNumber replaceOccurrencesOfString:#"-" withString:#"" options:NSBackwardsSearch range:NSMakeRange(0,[phoneNumber length])];
if([phoneNumber length] >=7) {
[phoneNumber insertString:#"-" atIndex:7];
}
if([phoneNumber length] >=3) {
[phoneNumber insertString:#"-" atIndex:3];
}
textField.text = phoneNumber;
You always return NO from the method, this means that in all cases you are not allowing textField to update the text through its internal logic, but you force it with the final statement
textField.text=newString;
This approach is correct, but your code contains a bug.
Infact suppose your current textfield string is "123-", as soon as you type backspace, the delegate is asked to replace "123-" with "123".
But in your code, you check that if the newString has length 3, then you append an extra "-".
So as soon as you type backspace to remove "-", then your code replace it with an extra "-".
In my opinion to fix it you should check if the textField.text length is > than newString. If so, then you are "deleting" and then you don't do the charCount==3 check, while if the textField.text length < newString length, then you are entering characters and you can do the check.
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
NSLog(#"%#", mobileNumber);
int length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(#"%#", mobileNumber);
}
return mobileNumber;
}
-(int)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:#"+" withString:#""];
int length = [mobileNumber length];
return length;
}
Related
Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!
Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321
convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321
You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];
NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf
Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!
Im having a issue with removing special characters from the string .I used the following code.But dint work.Please suggest me better logic
- (NSString *)trimmedReciString:(NSString *)stringName
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"-/:;()$&#\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
for (int i = 0; i < [stringName length]; i++) {
unichar c = [stringName characterAtIndex:i];
if ([myCharSet characterIsMember:c]) {
NSLog(#"%#",[NSString stringWithFormat:#"%c",[stringName characterAtIndex:i]]);
stringName = [stringName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"%c",[stringName characterAtIndex:i]] withString:#""];
}
}
return stringName;
}
NSString *s = #"$$$hgh$g%k&fg$$tw/-tg";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"-/:;()$&#\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"String is: %#", s);
Try this...
NSString *unfilteredString = #"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);
Try starting from the end of the string and work backwards instead of going from front to back, since you're likely to accidentally (and unintentionally) skip characters when the previous character gets deleted.
I have an application where I have I a textfield where user enters his mobile number including his country code. The format of the mobile number to be entered is +91-9884715715. When the user enters his/her mobile number initially validation should be performed that the first value entered by user is '+' and then the number that is entered after + should not be less that 0.
But after this I am getting confused that how to get the number of numbers entered between + and -, because user enters the country code and the length of numbers entered between + and - must be dynamic not static.
Try this ., might help you
- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:
(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textField == self.yourphoneNumberfield) {
NSArray *sep = [newString componentsSeparatedByString:#"-"];
if([sep count] >= 2)
{
countryCode = [NSString stringWithFormat:#"%#",[sep objectAtIndex:0]];
if ([[countryCode substringToIndex:1] isEqualToString:#"+"]) {
phoneNumber = [NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return ([countryCode length]+[phoneNumber length]);
}
}
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(#"Phone Number : %#",phoneNumber);
if (textField == self.yourphoneNumberfield) {
if ([phoneNumber length]<10)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Please Enter a Valid Mobile number" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
Try This:
NSString *code=#"+91-99999999";
NSRange rr2 = [code rangeOfString:#"+"];
NSRange rr3 = [code rangeOfString:#"-"];
int lengt = rr3.location - rr2.location - rr2.length;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
code = [code substringWithRange:aa];
NSLog(#"%#",code);
Goto XIB interface Builder and open xib document select ur phone number type textfield and go to textfield attribute, In the Text Input Traits, select Keyboard option from Default to Phone Pad.
// limit the input to only the stuff in this character set, so no emoji or any other insane characters
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"1234567890"];
if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
return NO;
}
Refer #Bala's answer
NSString *call = #"+91-9884715715";
// Search for the "+a" starting at the end of string
NSRange range = [call rangeOfString:#"+" options:NSBackwardsSearch];
// What did we find
if (range.length > 0)
NSLog(#"Range is: %#", NSStringFromRange(range));
Edit
Refer following link: TextField Validation With Regular Expression
Change the line
- (BOOL)validateInputWithString:(NSString *)aString
{
NSString * const regularExpression = #"^([+]{1})([0-9]{2,6})([-]{1})([0-9]{10})$";
NSError *error = NULL;
Add the code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
char *x = (char*)[string UTF8String];
//NSLog(#"char index is %i",x[0]);
if([string isEqualToString:#"-"] || [string isEqualToString:#"+"] || [string isEqualToString:#"0"] || [string isEqualToString:#"1"] || [string isEqualToString:#"2"] || [string isEqualToString:#"3"] || [string isEqualToString:#"4"] || [string isEqualToString:#"5"] || [string isEqualToString:#"6"] || [string isEqualToString:#"7"] || [string isEqualToString:#"8"] || [string isEqualToString:#"9"] || x[0]==0 ) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 18) ? NO : YES;
} else {
return NO;
}
}
Edit
Tested with demo:
//// Button Press Event
-(IBAction)Check:(id)sender{
BOOL check = [self validateInputWithString:TextField.text];
if(check == YES){
NSLog(#"Hii");
NSString *string= [NSString stringWithFormat:#"%#", TextField.text];
NSArray *first = [string componentsSeparatedByString:#"-"];
NSString *second = [first objectAtIndex:1];
NSString *third = [first objectAtIndex:0];
if([second length] < 11){
NSLog(#"bang");
}
else{
NSLog(#"Fault");
}
if([third length] > 3 || [third length] < 7){
NSLog(#"Bang");
}
else{
NSLog(#"fault");
}
}
else{
NSLog(#"FAULT");
}
}
I want user to not use any extra spaces in the text field. How to do that?
Description : I have a text field which I am using for "Title of Something". I don't want to allow any user to give extra spaces/only spaces.
Regards
Here small snippet for UITextFieldDelegate:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([[textField text] length] > 0) {
if([[textField text] characterAtIndex:([[textField text] length]-1)] == ' ' &&
[string isEqualToString:#" "]) return NO;
}
return YES;
}
You can trim the string when received:
NSString *string = #" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(trimmedString)
Also if you want to remove any double spaces inside the string i think this would do the trick:
NSString *noSpaces = [[string componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: #" "];
just try this
NSString *t1= [txt.text stringByReplacingOccurrencesOfString:#" " withString:#""]
i need to enter mobile number in a text field.
i need to display mobile number like this format 123-456-7890.
for eg: 1234567890 is my mobile number,while am entering this mobile number in text field,
for first 3 digits i need to place -,after 3 digits again i need to place -.
if i enter 123 then automatically place - in text field,after 456 place ,no need of placing for further 4 digits.
similar to displaying text in currency format.
but while getting text from that text field i need to get mobile number no need of - like 1234567890,not 123-456-7890.
i think my question is quite clear now,let me add comment if is not.
Thank u in advance.
Just to clarify: As a user enters a phone number into a UITextField, you would like it to automatically insert dashes in the proper places.
The answer is in using the UITextFieldDelegate protocol.
1) Set your controller object as a delegate for the UITextField.
2) You'll find the following method in the protocol:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
This method is called every time a character change occurs in the text field.
3) How robust you want your implementation to be is up to you. You could simply do a count of the current characters and insert dashes after 3 and 6 characters. It would be wise to also reject any non-numeric characters.
Here is a sample implementation. We basically take over the field editing manually - Inserting dashes after the appropriate string lengths and making sure the user can only enter numbers:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
if (charCount == 3 || charCount == 7) {
newString = [newString stringByAppendingString:#"-"];
}
textField.text = newString;
return NO;
}
Updated Matthew McGoogan's code : This works fine with back space also..
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField.tag == 8) {
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if (charCount == 3 || charCount == 7) {
if ([string isEqualToString:#""]){
return YES;
}else{
newString = [newString stringByAppendingString:#"-"];
}
}
if (charCount == 4 || charCount == 8) {
if (![string isEqualToString:#"-"]){
newString = [newString substringToIndex:[newString length]-1];
newString = [newString stringByAppendingString:#"-"];
}
}
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 12) {
return NO;
}
textField.text = newString;
return NO;
}
return YES;}
I used Matthews post above as a base.
This will format as so: (444) 444-4444
It also handles backspaces, unlike the answer above.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == _txtPhone1 || textField == _txtPhone2 || textField == _txtPhone3 || textField == _txtPhone4)
{
NSCharacterSet *numSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-() "];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
int charCount = [newString length];
if ([newString rangeOfCharacterFromSet:[numSet invertedSet]].location != NSNotFound
|| [string rangeOfString:#")"].location != NSNotFound
|| [string rangeOfString:#"("].location != NSNotFound
|| [string rangeOfString:#"-"].location != NSNotFound
|| charCount > 14) {
return NO;
}
if (![string isEqualToString:#""])
{
if (charCount == 1)
{
newString = [NSString stringWithFormat:#"(%#", newString];
}
else if(charCount == 4)
{
newString = [newString stringByAppendingString:#") "];
}
else if(charCount == 5)
{
newString = [NSString stringWithFormat:#"%#) %#", [newString substringToIndex:4], [newString substringFromIndex:4]];
}
else if(charCount == 6)
{
newString = [NSString stringWithFormat:#"%# %#", [newString substringToIndex:5], [newString substringFromIndex:5]];
}
else if (charCount == 9)
{
newString = [newString stringByAppendingString:#"-"];
}
else if(charCount == 10)
{
newString = [NSString stringWithFormat:#"%#-%#", [newString substringToIndex:9], [newString substringFromIndex:9]];
}
}
textField.text = newString;
return NO;
}
}
Use
NSString* number = [textField.text stringByReplacingOccurrencesOfString: #"-" withString: #""];