How to make textfield accept decimal inputs in iphone - iphone

I have a calculator app in which I have a textfield in which if I enter any number; then it works fine. If I do not enter a number then it shows alert. I also want the user to be able to enter 1.5 but when I do this it shows alert "enter a number please"
So how can I enter decimal number? I am using the following code :
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
NSString*string=costToClientTextField.text;
if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Warning" message:#"Only a number can be entered into this input field " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
costToClientTextField.text=#"";
}

Add the "." in your set, like so
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
return NO;
}
else
{
return YES;
}
}
Maybe this will help you. also put keyboard type number and punctuation.

Related

Local search in NSMutalbleArray

I want to search in NSMutalbleArray, my code is :
arrCelebs=[[NSMutableArray alloc] initWithObjects:#"Test 1",#"Test 2",#"Test 42",#"Test 5", nil];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *arrString1 = txtSearch.text;
NSRange tmprange;
for(NSString *string in arrCelebs) {
tmprange = [arrString1 rangeOfString:string];
if (tmprange.location != NSNotFound) {
NSLog(#"String found");
break;
}
}
return YES;
}
if i enter "t" then it search all the data and i want to add it another array. for display in tableview.
You can use the power of NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[c] %#", textField.text];
NSArray *filteredArray = [arrCelebs filteredArrayUsingPredicate:predicate];
By using predicate you Can easily get the result efficiently.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", txtSearch.text];
NSArray *ResultArray = [yourArray filteredArrayUsingPredicate:predicate];
return YES;
}
Try :
arr_NewArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [arr_YourArrayToSearch count]; i++)
{
NSString *curString = [string lowercaseString];
NSString *curStringInArray = [[arr_YourArrayToSearch objectAtIndex:i]lowercaseString];
if (![curString rangeOfString:curStringSmall].location == NSNotFound)
{
[arr_NewArray addObject:[arr_YourArrayToSearch objectAtIndex:i]];
}
}
arr_NewArray will give you the array with data matched to your search string.
arrCelebs=[[NSMutableArray alloc] initWithObjects:#"Test 1",#"Test 2",#"Test 42",#"Test 5", nil];
_resultArray = [[NSMutableArray alloc] init];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *arrString1 = txtSearch.text;
NSRange tmprange;
_resultArray = [[NSMutableArray alloc] init];
for(NSString *string in arrCelebs) {
tmprange = [arrString1 rangeOfString:string];
if (tmprange.location != NSNotFound) {
[_resultArray addObject:string];
}
}
return YES;
}
IF YOU work With UITableView then you cal also put this type of Logic.
Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following delegate Method of UISearchBar
- (BOOL) textFieldDidChange:(UITextField *)textField
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
}
Output Show in your Consol.
This exact what you want...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableArray *resultAry = [[NSMutableArray alloc] init];
for(NSString *string in arrCelebs)
{
NSRange range = [string rangeOfString:textField.text options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
[resultAry addObject:string];
}
}
yourTableAry=[resultAry mutableCopy];
[yourTable reloadData];
return YES;
}

Textfield Input Validation in iPhone SDK

I have to put validation on a UITextField for user input.
The user must input into the textfield a value
i.e. 70-80 or 85 mean num-num or num
Right now, I just allow to user to input only digits& - but drawback is that user can also input - number of times.
// My code is as follow
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789-"] invertedSet];
if (([txtMarks.text rangeOfCharacterFromSet:set].location != NSNotFound )||[txtMarks.text isEqualToString:#""] ) {
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Invalid Input" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
Simply Try this,
int times = [[txtMarks.text componentsSeparatedByString:#"-"] count]-1;
if(times>1)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"'-' used more than one" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
EDIT 1
Using NSPredicate we can do it. Try this,
NSString *regex = #"[0-9]+(-[0-9]+)?";
NSPredicate *testRegex = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if([testRegex evaluateWithObject:textField.text])
NSLog(#"Match");
else
NSLog(#"Do not match");
Hope that can help.
Try this first find whether your string contains -
Here subtring is -
if ([txtMarks.text hasPrefix:#"-"]||[txtMarks.text hasSuffix:#"-"])
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"sorry " message:#"invalid inoput as it has - at start or end" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
NSRange textRange;
textRange =[string rangeOfString:substring];
if(textRange.location == NSNotFound)
{
//Does not contain the substring
NSlog(#" string contains only num")
}
else
{
int times = [[txtMarks.text componentsSeparatedByString:#"-"] count];
if(times==2)
{
Nslog(#"num-num input")
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"'-' used more than one" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
}
}
Try it using the following regular expression, It restricts user to enter more than one -.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = #"^([0-9]{1,}+)?(\\-([0-9]{1,})?)?$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
{
return NO;
}
return YES;
}

NSRegularExpression on NSString not working

InUITextBoxfield,i insert some value,and I Want to use RegularExpressions match the string ..now i want the text box text should be match for only numeric digits upto 3 when I press button then it should work...
What I am trying is which is not working::-
-(IBAction)ButtonPress{
NSString *string =activity.text;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:#""];
if ([activity.text isEqualToString:modifiedString ])
{ // work only if this matches numeric value from the text box text
}}
- (BOOL)NumberValidation:(NSString *)string {
NSUInteger newLength = [string length];
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return (([string isEqualToString:filtered])&&(newLength <= 3));
}
in your button action event just use this like bellow...
-(IBAction)ButtonPress{
if ([self NumberValidation:activity.text]) {
NSLog(#"Macth here");
}
else {
NSLog(#"Not Match here");
}
}
Your code replaces all matches with an empty string, so if there is a match, it will be replaced by an empty string and your check will never work. Instead, just ask the regular expression for the range of the first match:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^[0-9]{1,3}$" options:NSRegularExpressionCaseInsensitive error:NULL];
NSRange range = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if(range.location != NSNotFound)
{
// The regex matches the whole string, so if a match is found, the string is valid
// Also, your code here
}
You can also just ask for the number of matches, if it's not zero, the string contains a number between 0 and 999 because your regex matches for the whole string.
Please try following code.
- (BOOL) validate: (NSString *) candidate {
NSString *digitRegex = #"^[0-9]{1,3}$";
NSPredicate *regTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", digitRegex];
return [regTest evaluateWithObject:candidate];
}
-(IBAction)btnTapped:(id)sender{
if([self validate:[txtEmail text]] ==1)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Correct id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message" message:#"You Enter Incoorect id." delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
}
}

how to show single dot using custom Number pad in iphone?

i am creating custom NumberPad
if (([[[UIDevice currentDevice] systemVersion] doubleValue] >= 4.1)) {
inputBoxTextField.keyboardType = UIKeyboardTypeDecimalPad;
}
my problem is, i want to display dot only one time.
thanks in advance.
If you want to allow the user to enter only one dot, you can use the delegate method
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
And simply check if the textField already contains a dot.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
return NO;
}
else {
return YES; } }
I use the following code. Works perfectly for me and with less code.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *decimalSymbol = [numberFormatter decimalSeparator];
if(([textField.text rangeOfString:decimalSymbol].location != NSNotFound) &&
([string rangeOfString:decimalSymbol].location != NSNotFound)) {
return NO;
}
return YES;
}

Delete key event in iPhone

I created UITextField. I need only 4 numeric characters only allowed that textfield.
I used the following code and get result.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
NSUInteger newLength = [passwordfield.text length];
if(newLength>=4)
{
[passwordfield setText:[passwordfield.text substringToIndex:3]];
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:#"Alert"];
[alert setMessage:#"Four Characters only allowed.."];
[alert setDelegate:self];
[alert addButtonWithTitle:#"Ok"];
[alert show];
}
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length]))
{
return NO;
}
else
{
return YES;
}
}
But my problem is when I press delete key, last two characters are deleting
and same time alertview also display.
How to solve this issue?
You're making this more complex than it needs to be. When a user taps the backspace key, the incoming string is a blank string; [NSString string]. Here's a working solution:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
if (![numberFormatter numberFromString:string] && ![string isEqualToString:[NSString string]]) {
return NO;
}
if (textField.text.length + string.length > 4) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert"
message:#"Four Characters only allowed..."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
} else {
return YES;
}
}