I'm using the following method to filter out non numeric characters when the user is entering content on the textfield:
#define NUMBERS #"0123456789"
- (BOOL)textField:(UITextField *)textFieldBeingChanged shouldChangeCharactersInRange:(NSRange) range replacementString:(NSString *)string
{
NSCharacterSet *cs;
NSString *filtered;
// Check for period
if ([textFieldBeingChanged.text rangeOfString:#"."].location == NSNotFound)
{
cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
}
However it blocks out the keyboard Return key as well, meanning by pressing the "return" key the
code to resignFirstResponder is not being called. Any way to resolve this? How should i check if the 'return' keywas pressed?
Thanks
A
Related
I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.
1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled
2 - How can i know if the textFiled is filled only with blank spaces
edit - It is invalid to enter only white spaces(blank spaces)
You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.
NSString *rawString = [textField text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0) {
// Text was empty or only whitespace.
}
If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:
NSRange range = [rawString rangeOfCharacterFromSet:whitespace];
if (range.location != NSNotFound) {
// There is whitespace.
}
If you want to prevent the user from entering whitespace at all, see #Hanon's solution.
if you really want to 'restrict' user from entering white space
you can implement the following method in UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}
If user enter space in the field, there is no change in the current text
Use following lines of code
NSString *str_test = #"Example ";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound)
{
NSLog(#"Found");
}
if you want to restrict user use below code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#" "])
{
return NO
}
else
{
return YES
}
}
UPD: Swift 2.0 Support
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let whitespaceSet = NSCharacterSet.whitespaceCharacterSet()
let range = string.rangeOfCharacterFromSet(whitespaceSet)
if let _ = range {
return false
}
else {
return true
}
}
I had a same condition not allowing user to input blank field
Here is my code and check statement
- (IBAction)acceptButtonClicked:(UIButton *)sender {
if ([self textFieldBlankorNot:fullNametext]) {
fullNametext.text=#"na";
}
// saving value to dictionary and sending to server
}
-(BOOL)textFieldBlankorNot:(UITextField *)textfield{
NSString *rawString = [textfield text];
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
if ([trimmed length] == 0)
return YES;
else
return NO;
}
Heres Swift 3 version
let whitespaceSet = NSCharacterSet.whitespaces
let range = string.rangeOfCharacter(from: whitespaceSet)
if let _ = range {
return false
}
else {
return true
}
In Swift,
if you want to restrict the user, you can use contains()
For Example,
if userTextField.text!.contains(" "){
//your code here.....
}
Here's what I did using stringByReplacingOccurrencesOfString.
- (BOOL)validateFields
{
NSString *temp = [textField.text stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSLiteralSearch
range:NSMakeRange(0, textField.text.length)];
if ([temp length] == 0) {
// Alert view with message #"Please enter something."
return NO;
}
}
#Hanon's answer is the pretty neat, but what I needed was to allow at least 1 white space, so based on Hanon's solution I made this one:
I declared a local variable called whitespaceCount to keep the counts of the white spaces.
Hope this helps anybody!
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([string rangeOfCharacterFromSet:whitespaceSet].location != NSNotFound)
{
whitespaceCount++;
if (whitespaceCount > 1)
{
return NO;
}
}
else
{
whitespaceCount = 0;
return YES;
}
}
I am trying to create a questionnaire, in which the user shall rate statements from 1-7.
The user rates the statements by filling UITextFields with a value between 1-7.
I have made it so that the user can only write in values between 1-7 and that they only can write one character per textfield.
What I want to do now is to prevent the user from using that value more than once.
This is the code that I have so far.
#define CHARACTERS #"1234567"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
return NO;
else
return YES;
}
I would use a dictionary. Whenever a number is chosen in a textfield, check if the dictionary has that value. If it doesn't have the value, the value entered is correct. Add the entry into the dictionary now and then let the user proceed to the next textfield. If you repeat this process for all the textfields you will be able to solve this problem pretty easily.
You can do one thing give tag to all textfields and check whether string you entered in current textfield is same as text of all other textfields then return NO.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
// These are the characters that are ~not~ acceptable
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet];
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1 ) | ([newString length] > 1) )
return NO;
else
//Call function to check if string is same as other textfield.text then return NO else YES
}
else
another option is you can take 1 string and save textfield.text in that string and update all time when you enter and check with it whether the string you are entering is in substring of that string.
best of luck
At the time of creating UITextField set the keyboardType as UIKeyboardTypeNumberPad.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([[textField text]length]==1)
//perform condition
else
//perform condition
}
this might help
I want to have runtime validation on my UITextField, i.e. when user starts entering data, it should validate and pop up error message if not correct. How do I implement this feature ?
textfieldDidChange or textFieldShouldEndEditing can be of any help ?
Any tutorial ?
You can implement the textField:shouldChangeCharactersInRange:replacementString: method on your text field's delegate, rejecting any characters that are invalid for your textfield. See the UITextFieldDelegate protocol reference for more information.
For example, if you only want to allow entry of decimal numbers, you could use:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
}
This won't actually pop up an error message if the input is incorrect; instead, it will prevent entry of characters that are incorrect.
If you do want to allow the user to type invalid characters, and them give them an error, you could implement this in the textFieldShouldEndEditing: method of your delegate.
This is a better solution since it allows backspaces.
Taken from :Hugo Larcher's blog
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *nonNumberSet;
if (textField == self.priceField) //allow decimals
nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
else
nonNumberSet=[[NSCharacterSet characterSetWithCharactersInString:#"0123456789"] invertedSet];
// allow backspace
if (range.length > 0 && [string length] == 0) {
return YES;
}
// do not allow . at the beggining
if (range.location == 0 && [string isEqualToString:#"."]) {
return NO;
}
// set the text field value manually
NSString *newValue = [[textField text] stringByReplacingCharactersInRange:range withString:string];
newValue = [[newValue componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:#""];
textField.text = newValue;
// return NO because we're manually setting the value
return NO;
}
i want to validate a text field to accept only characters while typing in it.....
I use the following for integers but I guess you could easily modify it to scan for strings/chars (see NSScanner):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
// This allows backspace
if ([resultingString length] == 0) {
return true;
}
NSUInteger holder;
NSScanner *scan = [NSScanner scannerWithString: resultingString];
return [scan scanInteger: &holder] && [scan isAtEnd];
}
Don't forget to set the UITextField delegate appropriately :)
I have a bitmap font which which doesn't have every single character, such as accented characters (é î ü etc) or symbols such as "¥" or © which I'm using to display usernames in a Highscore table for a game.
Is it possible to limit the UIKit keyboard to certain characters, or only allow certain characters in the UITextField? Or will I have to roll my own input mechanism? I'm thinking and old school, Arcade style, one letter at a time "thing" would be ok.
Using the UITextFieldDelegate method mentioned by intregus, you can do this quite easily:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// Only characters in the NSCharacterSet you choose will insertable.
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefgABCDEFG"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
You could try using the following UITextFieldDelegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
try using the UIKeyboardTypeNamePhonePad for your UITextField. It only has letters and numbers on it:
textField.keyboardType = UIKeyboardTypeNamePhonePad;
Using Interface builder you can link and get the event for "Editing changed" in any of your function. Now there you can put check for the length
- (IBAction)onValueChange:(id)sender
{
NSString *text = nil;
int MAX_LENGTH = 20;
switch ([sender tag] )
{
case 1:
{
text = myEditField.text;
if (MAX_LENGTH < [text length]) {
myEditField.text = [text substringToIndex:MAX_LENGTH];
}
}
break;
default:
break;
}
}