iphone - Price ui text field: how to allow user to enter only one decimal dot in to the text field for price like 283.99 -


this question has answer here:

i have tried code follow

this helps me allow user enter only numbers , dot (decimal point)

but problem user can allow n number of decimals in method.

i want allow 1 decimal

and 2 digits after decima

like 123.00 , 123423432353.99 but not 123.4.4 , 123.12345, 123...23

- (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string{         if (string.length == 0) {             return yes;       }       nscharacterset *mycharset = [nscharacterset charactersetwithcharactersinstring:@"0123456789."];       (int = 0; < [string length]; i++) {             unichar c = [string characteratindex:i];             if ([mycharset characterismember:c]) {                   return yes;             }       }       uialertview *av = [[uialertview alloc] initwithtitle:nil message:@"invalid input" delegate:self cancelbuttontitle:@"dismiss" otherbuttontitles:nil];       [av show];       return no;  } 

how allow user enter 1 decimal text field allow 2 digits after decimal

thanks in advance

best practices use regularexpressions whenever have perform string format validation email,phone number,currency etc.

this surely solve problem. here sample code below:

first create instance of nsregularexpression

nserror error; nsregularexpression * regexp = [[nsregularexpression alloc]initwithpattern:@"^\\d{0,10}(([.]\\d{1,2})|([.]))?$" options:nsregularexpressioncaseinsensitive error:&error]; 

then use in relevant method:

- (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range    replacementstring:(nsstring *)string {      nsstring * existingtext = textfield.text;     nsstring * completetext = [existingtext stringbyappendingformat:@"%@",string];      if ([regexp numberofmatchesinstring:completetext options:0 range:nsmakerange(0, [completetext length])])      {         if ([completetext isequaltostring:@"."])         [textfield inserttext:@"0"];         return yes;     }     else      return no;  } 

use , let me know if works.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -