Stop user from entering only spaces in textfield? - iphone

In my app I have a textfield in which users have to enter a string from 1-25 characters. The problem I'm having is stopping them from only entering spaces. I want them to be able to use spaces but only if they have other characters (abc, 1-9, etc.). How can I stop them from only entering spaces?

In your view controller set delegate of UITextField to self. Then implement following method.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
return NO;
}
return YES;
}

Sounds like this question might help.
Just trim the whitespace off the string and then check to see if it is the empty string.

Perform a whitespace "trim" on their input and check to see if the result matches an empty string.

Related

How enter only four value in text field from keyboard?

I am making an application in which i want to enter only numeric value. So i choose number pad type keyboard. Now i want that when user click on text filed and enter numeric value then enter only 0,1,2 and 3 not anything else. What i will do for that so i can apply restriction on text-field's value? And enter only single value not double value ie 11.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
}
Thanks in advances...
If rhe values are that restricted, you should try using a picker view or slider as the input view of the field.
How are you going to communicate to the user that 60% of the buttons on the numeric keypad are visible, enabled, tappable, but will do nothing?
in textField:shouldChangeCharactersInRange:replacementString: You can then check the character the user just entered for validity, returning NO for any invalid characters.
Here is a code sample to limit the size of a UITextField:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([[textField text] length] + [string length] - range.length > MAX_LENGTH) {
return NO;
} else {
return YES;
}
}
also see this

How to access character typed by user before showing it in UITextField

I'm writing application in which I need to validate text entered by user to UITextField, char by char with some method.
The difficult thing is that client wants to do all the validation before user see character in the UITextField because there might be situation that his server application doesn't support '$' sign, so in my validation method I should replace it with 'USD' string - and he doesn't want user to see '$', just 'USD' immediately.
I know about events like UIControlEventEditingChanged etc., but still, I don't know 2 things:
how to access character typed by user before it's seen in UITextField and execute validation there
how to subtitute this character 'on the fly' and put it manually to UITextField (but I suppose I'll just append this to [[textField] text] NSString
Thank You in advance for any help :)
Implement the UITextFieldDelegate method textField:shouldChangeCharactersInRange:replacementString:, e.g.:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL validated = ...; //do your validation
return validated;
}
Similar to omz's answer but more complete code if you need:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *filtered;
filtered = [string stringByReplacingOccurrencesOfString:#"$" withString:#"USD"];
//optionally if you want to only have alphanumeric characters
//NSMutableCharacterSet *mcs1 = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy]; //only alphabet character
//[mcs1 removeCharactersInString:#"0123456789"];
//filtered = [[filtered componentsSeparatedByCharactersInSet:mcs1] componentsJoinedByString:#""];
//release mcs1;
return [string isEqualToString:filtered];
}

Detect backspace in UITextField on a blank textfield [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Detect backspace in UITextField
I am trying to detect the backspace key envent on my UITextfield which is empty. I saw this but could not figure it out. Any elaborate answer or code snippet would be helpful
Detect backspace in UITextField
I've found it not to be possible.
When the UITextField is empty, the following delegate method isn't called.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
I conquered this by constantly having a space in the field, and when I detect a backspace and the field only contains a space, I return NO in the delegate method.
if ([string isEqualToString:#""] && [textField.text isEqualToString:#" "]){
// Backspace called on 'empty' field.
return NO;
}
Visually, this is as good as the field being empty, and it's a workaround to the delegate method not being called on an empty field.
Hope that helps.
:) just for the title "Detect backspace", where I use UIKeyboardTypeNumberPad.
I also meet the same question tonight, and following is my code to find it out:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog([NSString stringWithFormat:#"%d", [string length]]);
}
Because with UIKeyboardTypeNumberPad, user can only input Number or backspace, so when the length of string is 0, it must be backspace key.
Hope the above will do some help.

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;
}

Filtering characters entered into a UITextField

I have a UITextField in my application. I'd like to restrict the set of characters that can be can be entered into the field to a set that I have defined. I could filter the characters entered into the field when the text is committed using the UITextFieldDelegate method:
- (BOOL)textFieldShouldReturn:(UITextField*)textField
However, this gives the user a false impression as although restricted characters are removed from the final value, they were still visibly entered into the text field before pressing Return/Done/etc. What is the best approach that would prevent restricted characters appearing in the text field as they are selected on the keyboard?
Note: I am operating under the assumption that I have little control over which keys are provided by the iPhone keyboard(s). I am aware that I can switch between various keyboard implementations but am under the impression that I can't disable specific keys. This assumption may be incorrect.
I did as marcc suggested and it worked well. Sample implementation follows.
Note: Variable names were selected for brevity and do not reflect my coding standards:
...
myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"xyzXYZ"];
...
}
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered {
for (int i = 0; i < [textEntered length]; i++) {
unichar c = [textEntered characterAtIndex:i];
if (![myCharSet characterIsMember:c]) {
return NO;
}
}
return YES;
}
Look at textField:shouldChangeCharactersInRange
This method is called by the UITextFieldDelegate whenever new characters are typed or existing characters are deleted from the text field. You could return NO to not allow the change.
Here is one of the cleanest approaches to restricting characters entered in a UITextField. This approach allows the use of multiple predefined NSCharacterSets.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[allowedCharacters formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
if([string rangeOfCharacterFromSet:allowedCharacters.invertedSet].location == NSNotFound){
return YES;
}
return NO;
}
Look at the UITextViewDelegate method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string.
It's exactly what you need.
This is what I use to restrict the user to uppercase A-Z. Adjust the regex variable according to taste:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^A-Z]";
return ([string rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
How about this?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString* regex = #"[^a-z]";
return ([[string lowercaseString] rangeOfString: regex
options:NSRegularExpressionSearch].location == NSNotFound);
};
Note:
I am making all characters to lower case [string lowercaseString] so that you don't need to write in regex for captial/small letters.
You could loop and keep checking if the UITextField.text property has changed once the DidBeginEditing method gets called. If it has, check the text and remove an bad characters.