Format Integer with two decimal format in UITextfield - iphone

I am presenting the user with a field that displays the number keyboard and only want them to be able to enter numbers with decimal it should be only one. After decimal it is should be at least 2 digits will be there. There should be at least one digit before the decimal. Then the input can`t be 0 or 0.00. Suppose if user enter the number 123456 it is accepted then 123.56 it also accepted how can I do this one please help me.

you can make a regex for this requirement like:-
NSString *numberRegEx = #"[0-9]+[.]{0,1}+[0-9]{0,2}";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", numberRegEx];
//Valid email address
if ([numberTest evaluateWithObject:textField.text] == YES)
{
NSLog(#"correct value");
}
else
{
NSLog(#"incorrect value");
}

First, add a target for UIControlEventEditingChanged of your text field:
[textField addTarget:self action:#selector(onEdit:) forControlEvents:UIControlEventEditingChanged];
add a BOOL property to your class:
#property(nonatomic, assign) BOOL formatting;
then create an onEdit: method like this:
-(void)onEdit:(UITextField*)field {
//if you have more than one text field you can check for the one you need to format
if(!self.formatting) {
NSString* formattedText = ...//get the formatted text according to your rules
self.formatting = YES;//infinite loop prevention
field.text = formattedText;
self.formatting = NO;
}
}

You can impose all your conditions in the -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string method. Here, textField.text will be the most recent text that the user has entered. You can parse it and see whether any of your conditions are not being met. Return NO in that case.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(allConditionsMet)
return YES;
return NO;
}
HTH,
Akshay

Related

Calling a method only after shouldChangeCharactersInRange returns yes

I have a UITextField with a table below it showing a list of items to select from (similar to drop down list). Now for example when i type 2 in textfield (textfield has Year values), the table would show all strings with 2 as substring. So when i type in 2000, it would only show matching string 2000 in the table.
Now when i finish typing 2000 in the textfield i want to call a method. Everything works fine but i want to call this method only when i finish typing all 4 digits but here the method is called when i try to enter 4th digit.
How can i perform this where i type in 2000 and it will call the method after shouldChangeCharactersInRange return Yes after entering 3rd zero.
Here's my code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
//if _filteredarray count==1 and substring and _filteredarray object at index 0 matches then call a method here
return YES;
}
Try this
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
if(substring.length == 4)
{
[textField resignFirstresponder];
[self performSelector:#selector(functiontocall)withObject:nil afterDelay:0.8];
}
return YES;
}
the above code may give u an idea
if u enter fourth letter of 2000, then the keyboard will disappear(if u want u can add it, which will avoid further entering values to textfield), then u can see the third zero for 0.8 seconds and the function u need to call will be called.

shouldChangeCharactersInRange taking only one digit at time

i am trying to get total value after multiplying price and quantity in to text field. I not getting value when quantity is 10 or having any two or three digits.This method takes only one character at time.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
if(textField == quantityText)
{
NSCharacterSet *charactersToRemove =[[ NSCharacterSet alphanumericCharacterSet ]
invertedSet];
NSRange inRange=[string rangeOfCharacterFromSet:charactersToRemove];
if(inRange.location != NSNotFound)
{
quantityText.text =[ quantityText.text
stringByTrimmingCharactersInSet:charactersToRemove ];
return NO;
}
if ([textField text] )
{
float quantity = [string floatValue];
float price = [[priceLabel text] floatValue];
float h = quantity * price;
amountText.text=[NSString stringWithFormat:#"%f",h];
}
else
{
return NO;
}
}
return YES;
}
You're only using the replacementString value for your calculation, which is the last character that was typed, not the whole the whole string.
So if I type '1' then function uses 1 as the value, then if I type '0' to make 10, your function only uses the '0' as the value.
You need to get the whole text of the quantityText textfield and use that. You could get that by taking textField.text and then replacing the specified range with the replacementString.
To be honest though it's a lot easier just to register for the UITextFieldTextDidChangeNotification instead of using the textfield:shouldChangeCharactersInRange:replacementString: method.
See this answer for details.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
this delegate method is called whenever user types a new character in to the textfield and the string object will contain only the last typed character. so instead of using (NSString *)string use textField.text

How apply validation on text field with respect to value of another text filed?

I want to apply validation on text field. I have two text filed and i want to enter only 0-11 value when second text field value is equal to "AM". How apply validation text filed with respect to another text field's value?
Thanks in advance...
You can achieve your design by keeping references to both text fields in your view controller.
However, it would be much more conforming to Apple's Human Interface Guidelines to use a UIPickerView for choosing from a number of items less than 12.
try this way
- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
if(textField==self.txt1 && [self.txt2.text isEqualToString:#"AM"]){
[self.txt1 setKeyboardType:UIKeyboardTypeNumberPad];
}
return YES;
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:#""]) {
return YES;
}
if(textField==self.txt1 && [self.txt2.text isEqualToString:#"AM"]){
int no=[self.txt1.text intValue];
NSLog(#"%d",no);
int enteredno=[string intValue];
int sum=no*10+enteredno;
if (sum>11) {
return NO;
}
}
return YES;
}
Here txt1 and txt2 are first and second textfields. Set the delegate to both the textfields.
get the value from second textfiled and check then validate like
if([secTxtField.text isEqualToString:#"AM"])
{
//do the validation for the first
}
first check for only numbers here,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static NSCharacterSet *charSet = nil;
if(!charSet) {
charSet = [[[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet] retain];
}
NSRange location = [string rangeOfCharacterFromSet:charSet];
if(!(location.location == NSNotFound))
{
if([secTxtField.text isEqualToString:#"AM"])
{
//get the first textField input
//Conver to int
//Check for less than 11
if (pass)
{
return YES;
}
else
{
return NO;
}
}
}
return (location.location == NSNotFound);
}

Cococa Touch - Verifying each character inputed

I want to have the user type in something. And I want to verify each character inputed. How could I do this? I want it to be in real time. So as its typed its being verified and color coded.
You could compare what I want to do to an programmers IDE how it checks the syntax as you type it.
Any help is appreciated!
Connect the UITextField delegate to the app delegate and do something like:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if([string isEqual:#"b"]) {
// User typed 'b'
// Insert string with specific color
// [...]
} else {
// User typed something else
// Insert string without specific color
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
}
return YES;
}

delete last character UITextField

I have an UITextField and I would like that for every tap on a character, the first character is deleted. So that I just have one character in my textField every time. Moreover I would like it to display every tap in the console log.
How can I do this?
You need to implement shouldChangeCharactersInRange method in your text field delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
(NSRange)range replacementString:(NSString *)string{
textField.text = #"";
return YES;
}
You may need to check for range and string values to cover all possible cases (like copy/paste actions). This code just sets the text field's value to the last typed character.
UITextField inherits from UIControl, so you can use the target-action mechanism that is part of the UIControl class:
[textField addTarget:self action:#selector(updateTextField) forControlEvents:UIControlEventValueChanged];
In the action method, you can replace the UITextField's text with only the last character and log that character in the console. Note that since changing the UITextField's text will again result in the "updateTextField" message being sent a second time to the target, you will need some kind of mechanism for determining whether to update or not:
- (void)updateTextField {
if(updateTextField == YES) {
updateTextField = NO;
NSString *lastChar = [textField.text substringFromIndex:[textField.text length]];
[textField setText:lastChar];
NSLog(#"%#", lastChar);
} else {
updateTextField = YES;
}
}
Or something like that anyway...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField.text.length > 8) {
return NO;
}
return YES;
}