i want to restrict user from entering space in a UITextField. for this i m using this code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ( string == #" " ){
UIAlertView *error = [[UIAlertView alloc] initWithTitle:#"Error" message:#"You have entered wrong input" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[error show];
return NO;
}
else {
return YES;
}
}
but it is not working .... what is wrong in it ?
The problem is
string == #" "
is wrong. Equality for strings is done using:
[string isEqualToString:#" "]
:).
This will search to see if your replacement string contains a space, if it does then it throws the error message up, if it doesn't it returns YES.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSRange spaceRange = [string rangeOfString:#" "];
if (spaceRange.location != NSNotFound)
{
UIAlertView *error = [[UIAlertView alloc] initWithTitle:#"Error" message:#"You have entered wrong input" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[error show];
return NO;
} else {
return YES;
}
}
The current answer is this:
Set the View Controller to conform to the UITextFieldDelegate (should look something like this near the top of your code):
#interface YourViewController () <UITextFieldDelegate>
...
# end
# implementation YourViewController
...
#end
Then make the textfield use the View Controller as its delegate. Do this by going to the Interface Builder, control clicking on the textfield and dragging a line to the yellow circle on the bar underneath the View Controller, and selecting "delegate" from the menu that pops up. You could alternatively do this in code by setting the delegate after making the property described in the next paragraph. Do it this way with self.yourTextField.delegate = self; in an appropriate place, possibly in viewDidLoad.
Also set the textField up as a property on the View Controller. Do this by going to the Interface Builder, with its code open in the assistant editor, and control click and drag from the text field in the Interface Builder, to the place in the code where the properties are listed (between #interface and the first #end). Then enter a name in the pop up window. In the code below I used "yourTextField" for example. (you can skip this section, together with the outside if loop in the code below if you are sure that this is the only text field that will use the View Controller as its delegate, but it is best to plan ahead for future possibilities)
Then you can disallow spaces from even be entered using the following delegate method:
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.yourTextField)
{
if ([string isEqualToString:#" "] )
{
return NO;
}
}
return YES;
}
Try this (set this in your - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string):
NSArray *escapeChars = [NSArray arrayWithObjects:#" ", nil];
NSArray *replaceChars = [NSArray arrayWithObjects:#"",nil];
int len = [escapeChars count];
NSMutableString *temp = [[textField text] mutableCopy];
for(int i = 0; i < len; i++) {
[temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i] withString:[replaceChars objectAtIndex:i] options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
}
[textField setText:temp];
return TRUE;
string == #" "
Isn't that just going to compare the adress of each of string and #" "? Thats not the comparison you want to do.
Also do you want to prevent them from entering a string that is just a space? If so then you need to change that == into a proper string comparison and you are good to go. If not and you want to prevent all spaces in an input string then you need a string matcher
Below is what I am using for password and confirm password
In PrefixHeader.pch file add below
#define NONACCEPTABLE_PASSWORD_CHARACTERS #" "
And in code use below.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==passwordTF || textField==confirmPasswordTF) {
NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:NONACCEPTABLE_PASSWORD_CHARACTERS];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
return YES;
}
Related
This question already has answers here:
Limiting text field entry to only one decimal point
(10 answers)
Closed 9 years ago.
I have tried with this code as follow
this helps me to allow user to enter only numbers and dot (decimal point)
But the problem is user can allow n number of decimals in this method.
I want to allow only one decimal
and only two digits after the decima
like 123.00 , 123423432353.99
but not like 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."];
for (int i = 0; i < [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 to allow user to enter only one decimal the text field that too allow only two digits after the decimal
thanks in advance
Best practices Use RegularExpressions whenever you have to perform any string format validation like Email,Phone Number,Currency etc.
This surely will solve your 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 your 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 and let me know if it works.
Please try to use this one...It may helps you and please implement your functionality.This code for only 2 digit after "."
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;
can anyone tell how to access only alphabets through keyboard. Numbers and special characters should not de entered into the UILabel.
I'am new to iOS programming and I'am searching this from last 2 hours of no use. Help me out of this
try this ...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
{
static NSCharacterSet *charSet2 = nil;
if(textField==txtfirstname)
{
if(!charSet2)
{
charSet2 = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "] invertedSet];
}
NSRange location = [string rangeOfCharacterFromSet:charSet2];
return (location.location == NSNotFound);
}
}
Hope this helps...
To get a notification you'll have to use the delegate function of UITextField. If you use the UILabel. You might have to go ahead and use the Keyboard notifications. Instead what you can do is use the UITextField. You can use the UITextField border style property to make it look a like UILabel.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
for (int i = 0; i < [string length]; i++)
{
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
{
return YES;
}
else
{
return NO;
}
}
}
I'm trying to change the first letter of the user input to the uppercase in the method alertViewShouldEnableFirstOtherButton. Everything works as expected in the iOS 6 but in iOS 5 it seems I get the infinite loop(when I set the text field of the alert view programmatically it calls the method alertViewShouldEnableFirstOtherButton recursively )
Here it is the code:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if(inputText.length==0)return NO;
unichar firstChar=[[inputText capitalizedString] characterAtIndex:0];
NSString *capitalizedLetter= [NSString stringWithCharacters:&firstChar length:1];
NSString *str=[inputText stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:capitalizedLetter];
[[alertView textFieldAtIndex:0] setText:str];// setText calls again alertViewShouldEnableFirstOtherButton
return YES;
}
- (BOOL)alertViewShouldEnableFirstOtherButton: is for the alertView to ask its delegate whether the first (non-cancel) button should be enabled or not.
The alertView is free to call this method at any time (for instance it might call it when its textfields are changed), to get a YES/NO answer from the delegate. Therefore, you should not implement side effects here.
I would recommend using something like [alertView textFieldAtIndex:0].delegate = self and use one of the textField delegate methods (for instance – textFieldDidBeginEditing:) to modify the string.
Actually I used the shouldChangeCharactersInRange method of UITextField to capitalize the first letter of the inserted string.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(#"range: %# string: %#", NSStringFromRange(range), string);
if ([string isEqualToString:#""]) {// detect when the user removes symbol
if ([textField.text length] > 0)textField.text = [textField.text substringToIndex:[textField.text length] - 1];//remove last character from the textfield
}
if (range.location==0) {//capitalize first letter
NSString *upperString = [[textField.text stringByAppendingString:string] uppercaseString];
textField.text = upperString;
}else {
textField.text=[textField.text stringByAppendingString:string];
}
return NO;
}
I have iphone app in which i enter any number value like 10 2 0 1 0.2 etc i want that instead of this if user enter any text it should alert that enter a number.
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Value Must Be In Number " delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
try this code:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField==txtMobileNo)
{
[self validatePhone];
}else
{
[textField resignFirstResponder];
}
// called when 'return' key pressed. return NO to ignore.
return YES;
}
- (BOOL) validatePhone
{
NSString *phoneRegex = #"^+(?:[0-9] ?){6,14}[0-9]$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneRegex];
if ([phoneTest evaluateWithObject:txtMobileNo.text] == YES)
{
NSLog(#"proper phone nO ");
return YES;
}
else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:#"Please,Enter Your Person proper phone no" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil ];
[alert show];
[alert release];
NSLog(#"phone no. not in proper format");
return NO;
[txtMobileNo becomeFirstResponder];
}
}
I hope you helpful.
That disrupts the app kind of, doesn't it? What you want to look at is the UITextfield delegate methods. Set your viewController as the textields delegate and make it respond o UITextFieldDelegate protocol.
I would implement the textField:shouldChangeCharactersInRange:replacementString method and check the replacementString for unwanted characters.
But rather than displaying an alert, I guess I would just return NO if unwanted characters are contained there. Then, when the user enters something other than what you want, nothing happens.
you can check if it is a number using the following:-
NSString *yourString= #"121212";
NSCharacterSet *decimalNUmSet= [NSCharacterSet decimalDigitCharacterSet];
BOOL isNum= ([[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#""] ||
[[yourString stringByTrimmingCharactersInSet:decimalNUmSet] isEqualToString:#"."]);
here the second part includes decimal numbers also.
the other way is to present a numeric keyboard to user so that he can type only numbers.
You validate the entered character and do your logic in this delegate ,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// your logic to restriction goes here.like check the entered char and through alert
}
-(BOOL) validateNumericValue:(NSString*) textValue
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:textValue];
if (number != nil)
{
return YES;
}
return NO;
}
I'm having 4 textfields in my application
1.username
2.Email
3.Age
4.Password
User names are 3-25 characters and contain only the characters [a-z0-9]
Age must be between 1-100 inclusive.
Passwords are between 4-12 characters and use only the characters [a-zA-Z0-9]
how can i restrict the textfield with above requirements
please anyone help me out to do this..
Thank you for your effort and consideration.
You can use the methods in the UITextFieldDelegate protocol to validate your fields' content.
More concretely, either you use:
– textFieldShouldEndEditing:
- textFieldShouldReturn:
or you can use:
- textField:shouldChangeCharactersInRange:replacementString:
In the first case, you only validate when the user ends editing the text field; in the second case, you can do the validation at each keystroke.
In all of those methods, you receive an argument textField which you can access like this:
NSString* text = textField.text;
NSUInterger length = [text length];
if (length.....) {
// -- show alert or whatever
return NO;
}
You can validate numbers as the user type by implementing -[UITextField textField:shouldChangeCharactersInRange:replacementString:] method. Do note that this method is called before the change is made, so you need to construct the text that could be the result of the users actions yourself. For example:
-(BOOL)textField:(UITextField*)textField: shouldChangeCharactersInRange:(NSRange*)range
replacementString:(NSString*)string;
{
NSString* text = [textField.text stringByReplacingCharactersInRange:range
withString:string];
// text is now the potential string you should check against.
}
What you do from there is up to your own. Some examples could be:
// Too short?
if ([text length] < 4) ...
// Invalid character?
NSCharacterSet* invalidChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
if ([text rangeOfCharacterInSet:invalidChars].location != NSNotFound) ...
For more complex number validation I would use NSNumberFormatter, that has support for validating ranges and more.
You can use UITextFieldDelegate to get done what you want. Assign different values to textfield.tag for each field in - (void)viewDidLoad method and match those tag values to find the relevant field in the (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string.
#define USERNAME_FIELD_TAG 1
#define PASSWORD_FIELD_TAG 2
#define EMAIL_FIELD_TAG 3
#define AGE_FIELD_TAG 4
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tab == USERNAME_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[a-z0-9]{3,35}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == PASSWORD_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[a-zA-Z0-9]{4,12}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == EMAIL_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
else if (textField.tab == AGE_FIELD_TAG)
{
if([[NSPredicate predicateWithFormat:#"SELF MATCHES[cd] %#", #"[1-100]"] evaluateWithObject:string] == FALSE)
{
textField.text = [textField.text stringByReplacingOccurrencesOfString:string withString:#"" options:NSCaseInsensitiveSearch range:range];
[self selectTextForInput:textField atRange:range];
return NO;
}
}
return YES;
}
// place the cursor at given possition
-(void)selectTextForInput:(UITextField *)input atRange:(NSRange)range {
UITextPosition *start = [input positionFromPosition:[input beginningOfDocument]
offset:range.location];
UITextPosition *end = [input positionFromPosition:start
offset:range.length];
[input setSelectedTextRange:[input textRangeFromPosition:start toPosition:end]];
}