Restricting character input on iPhone UITextField [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
allow only alphanumeric characters for a UITextField
Is there a way of only letting the user input letters and numbers, no symbols, via the keyboard into a UITextField?

Use this delegate methods.. as It works for me..
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == YOUR TEXT FIELD)
{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
else
return YES;
}

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {
//return yes or no after comparing the characters
}

Try this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if(![string stringByTrimmingCharactersInSet:nonNumberSet].length)
{
return NO;
}
return YES;
}

Related

Filter out characters in one UITextField

Ok, I am trying to edit this one text field that is txtCountry to not accept certain letters, but I can't, because the txt country is not setup right. Can someone please fix this up for me. I probably making some kind of little detail mistake.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([textField isEqual: txtCountry]) {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:LEAGELNUM] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
BOOL basicTest = [string isEqualToString:filtered];
return basicTest;
}
}
You don't need to insert the name of the text field into the method. Instead do this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField isEqual: txtCountry]) {
//return YES or NO here depending on your criteria
}
}

Remove the last character typed in UItextfield

I need to remove the last character if the textfield length exceeds 100,I used the following code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textfield.text.length>=100)
{
NSString *text;
textField.text=text;
NSString *newString = [text substringToIndex:[text length]-1];
textField.text=newString;
}
return YES;
}
But it just erases the whole text.
You erase the whole text because of this line:
textField.text=text; // text is nil here
What you wanted to do is more likely the following:
NSString *text = textField.text;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textfield.text.length>=100)
{
NSString *text;
text =[[textField text] stringByAppendingString:string];
NSString *newString = [text substringToIndex:[text length]-1];
textField.text=newString;
}
return YES;
}
Paste the code may solve your issue
In iOS 5 or later:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([textField.text length] >= 100)
{
[textField deleteBackward];
}
}
try with the below code
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText {
NSString* newText = [textView.text stringByReplacingCharactersInRange:aRange withString:aText];
// CGSize strSize = [newText sizeWithFont:textView.font constrainedToSize:CGSizeMake(200, 10000) lineBreakMode:UILineBreakModeWordWrap];
if([newText length] > 100)
{
return NO; // can't enter more text
}
else
return YES; // let the textView know that it should handle the inserted text
}
try this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
return !([newString length] >100);
}
In order to fix the UITextField length you don't have to work with strings concatenation. Just use this simple code:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return !([string length]+[textField.text length] > FIXED_LENGTH);
}
This way you, as UITextFieldDelegate, are saying: "change the UITextField appending string to textField.text only if the sum of all characters doesn't exceed max length"
Here is an example how to remove any text in UITextField; applies to iOS 10.3 and later
#IBOutlet var upcText: UITextField!
if var textRange = upcText.selectedTextRange {
if textRange.isEmpty && textRange.start != upcText.beginningOfDocument {
// text has not been selected and the cursor is not at the beginnning
// then create new range to delete previous character
textRange = upcText.textRange(from: upcText.position(from: textRange.start, offset: -1)!, to: textRange.start)!
}
upcText.replace(textRange, withText: "")
}

shouldChangeCharactersInRange: method is not allowing to delete existing character

I am currently restricting the user to write in a text from more than 4 character.
For this i am using this piece of code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string{
if ([textField.text length] == 4)
return NO;
else
return YES;
}
Its working fine and it do not allow the user to write more than 4 character.
But when i try to delete the existing character.The keyboard delete option is not working.
How to solve this problem
When shouldChangeCharactersInRange method is called text field still has an old value and so if its length is 4 you're stuck. Better way to validate input will be to calculate what string you're going to have in a field after the change and check if it is valid:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range
withString:string];
return [newString length] <= 4;
}
write like below it will work
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength>4) ? NO : YES;
}

how to validate textfield that allows two digits after

i have to validate text field that allows only two digits after .
eg:12.34
if user enter more then two digits it won't allows text.
let me know is it understandable or no
how can i done,can any one please help me.
Thank u in advance.
You should code in the following delegate method,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSArray *sep = [string componentsSeparatedByString:#"."];
if([sep count]==2)
{
NSString *sepStr=[NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
if([sepStr length] >2)
//do whatever you want
}
}
You can also check if they use many decimal points by,
if([sep count]>2)
//use only one decimal point
I resolve my problem by using this code.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *sep = [newString componentsSeparatedByString:#"."];
if([sep count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:#"%#",[sep objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
}
Check the text validity in text field delegate:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Iphone UITextField only integer

I have a UITextField in my IB and I want to check out if the user entered only numbers (no char)and get the integer value.
I get the integer value of the UITextField like that :
int integer = [myUITexrtField.text intValue];
When I put a character ( , ; . ) it return me 0 and I don't know how to detect that it is not only numbers.
How can I do?
Implementing shouldChangeCharactersInRange method as below does not allow the user input non-numeric characters.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:#""];
}
This returns YES if the string is numeric, NO otherwise. the [string isEqualToString#""] is to support the backspace key to delete.
I love this approach because it's clean.
Be sure to set your text field delegate
Use the following function to ensure user can type in numbers only:
- (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;
}
}
Try this: It will stop user to enter any character other then numbers
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
{
return NO;
}
return YES;
}
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Objective-C
Or you could ensure that only the numeric keyboard appears when the focus comes on the field
To only allow for numeric input:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
return [string isEqualToString:#""] ||
([string stringByTrimmingCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].length > 0);
}
To test for an integer:
- (BOOL)isNumeric:(NSString *)input {
for (int i = 0; i < [input length]; i++) {
char c = [input characterAtIndex:i];
// Allow a leading '-' for negative integers
if (!((c == '-' && i == 0) || (c >= '0' && c <= '9'))) {
return NO;
}
}
return YES;
}
Answer by #devsan is incorrect. If a user pastes anything with a a number such as "1abc" her code would break
It should be (allow replacement only if all the chars are digits):
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length == string.length) || [string isEqualToString:#""];
}
You could also use UITextFieldDelegate method
textField:shouldChangeCharactersInRange:replacementString:
to live check that each time the user press a key, it is a simple digit, so that he/she knows that only int value is to be entered in the field.
Want to allow negative numbers as well?
Elaborating on davsan's answer, here is a solution that supports entering negative as well as positive numbers, and disallows anything else.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:#""] || ([textField.text isEqualToString:#""] && [string isEqualToString:#"-"]);
return YES;
}
This code is work with localisation too .
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#""]) return YES;
NSCharacterSet *characterSet = nil;
characterSet = [NSCharacterSet decimalDigitCharacterSet];
NSRange location = [string rangeOfCharacterFromSet:characterSet];
return (location.location != NSNotFound);
if(characterSet == nil) return YES;
return YES;
}