Check the content of NSString with data in NSArray - ios

I have the next problem:
In a UITextField, I need to check if the user inserts an invalid character for the Name, like [ ] { }.
My question is, how can I check the content of the UITextField with one NSArray with the invalid characters inside?

If you want to check single letter input from keyboard on some input politics
you need to use textField delegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
You should check if string contains in your exception array. If so you return NO and symbol doesn't appear on screen.

Ok, I explain what I do to solve the problem. Cause I'm controlling the behavior of a UITextField where I use to the user enter the name and one comment, I make a character set with all characters I allow and I put inside the shouldChangeCharactersInRange Method:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:#" ,.abcdefghijklmnopqrstuvwxyzçñ?!'ABCDEFGHIJKNMLOPQRSTUVWXYZÇÑ-_;:0123456789+*()-/#áàéèíìóòúù"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}

Related

add prefix to UITextField

I want to add prefix of UITextfield text. The UITextfield text length less than 7. How many characters are less than 7, that all replace with zeros.
If text is "1234", add prefix like "0001234".
If text is "12345", add prefix like "0012345".
If text is "123", add prefix like "0000123".
can any one suggest me, how to implement.
It sounds like what we actually want is a numbers-only string that is always 7-characters long, with the left-most characters filled in with padded zeros for anything the user has not entered, correct?
So, we need a handful of methods to make this as easy as possible.
First, this one doesn't make sense right now, but we want a method to remove the zeros we padded at the front (it'll make sense later).
So, borrowing from this Stack Overflow answer...
- (NSString *)stringByRemovingPaddedZeros:(NSString *)string {
NSRange range = [string rangeOfString:#"^0*" options:NSRegularExpressionSearch];
return [string stringByReplacingCharactersInRange:range withString:#""];
}
And we'll borrow from Ilesh's answer for adding the padded zeros:
- (NSString *)stringByAddingPaddedZeros:(NSString *)string padLength:(NSInteger)length {
NSString *padding = [#"" stringByPaddingToLength:(length - string.length) withString:#"0" startingAtIndex:0];
return [NSString stringWithFormat:#"%#%#", padding, string];
}
So now we can go back and forth between padded and unpadded strings, right?
So now, one last step, implementing shouldChangeCharactersInRange:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
newString = [self stringByRemovingPaddedZeros:newString];
newString = [self stringByAddedPaddedZeros:newString padLength:7];
textField.text = [newString subStringToIndex:7];
return NO;
}
We always return NO here, as we're setting the textField.text property manually. Now when there are 7 characters (and no leading zeros), the user can type no more. If there are 7 characters and the user hits backspace, they should all shift right one and a zero added to the front. If there are leading zeros at the front, typing characters should shift everything left and drop a leading zero, and add a new character to the front.
As an additional note, this code does not take care of verifying that the user is only entering digits. Some extra logic would be required for that. I'd simply recommend checking that the replacementString (string) is only digits before you get into any of the other code in shouldChangeCharactersInRange here.
Here printing textfield text on button click. Check the code inside the method.
- (IBAction)logTextFieldText:(id)sender
{
NSMutableString *str=[[NSMutableString alloc]init];
if (_txtf.text.length<7)
{
for (int i=0;i<7-_txtf.text.length; i++)
{
[str appendString:#"0"];
}
[str appendString:_txtf.text];
}
NSLog(#"final text is: %#",str);
}
Implement the UITextFieldDelegate method textFieldDidEndEditing: to pad the 0's in.
- (void)textFieldDidEndEditing:(nonnull UITextField *)textField
{
if (textField.text.length < 7) {
// Create a string of 0's to pad with
NSString *padding = [#"" stringByPaddingToLength:(7 - textField.text.length) withString:#"0" startingAtIndex:0];
NSMutableString *change = [textField.text mutableCopy];
// Insert the 0's string
[change insertString:padding atIndex:0];
textField.text = change;
}
}
If you want to fix the length of UITextField text than use this UITextField delegate method.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (self.txtGet.text.length>=7) {
return NO;
}
return YES;
}
and the completion editing (or done button ) you add this line in before using the UITextField value.
NSString *padding = [#"" stringByPaddingToLength:(7 - self.txtGet.text.length) withString:#"0" startingAtIndex:0];
NSMutableString *change = [self.txtGet.text mutableCopy];
// Insert the 0's string
[change insertString:padding atIndex:0];
self.txtGet.text = change;
I think its helpful to you. Thank you.

Restrict user to enter abuse words in text view

I am developing a application where user has to enter only holy words. I want user to be restricted not to enter the abuse or adult word.
I have a big list of adult or abuse words whenever user will enter that word it should delete it automatically.
Any help will be appreciated.
You are probably using UITextField so you should look after forbidden words after text has changed:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSRange spaceRange = [newString rangeOfString:#" "];
if (spaceRange.location != NSNotFound) { // it's a new word
newString = [self stringWithoutForbiddenWords:newString];
}
textField.text = newString;
return NO; // we set the textField text manually
}
- (NSString *)stringWithoutForbiddenWords:(NSString *)string {
for (NSString *forbiddenWord in self.forbiddenWords) {
NSRange forbiddenWordRange = [string rangeOfString:forbiddenWord];
if (forbiddenWordRange.location != NSNotFound) {
// remove the forbidden word
string = [string stringByReplacingOccurrencesOfString:forbiddenWord withString:#""];
}
}
return string;
}
Don't forget to set you UITextField delegate.
Its a very simple logic , by the way only "Holy Word" seems very funny I hope you meant non-abusive words.
So to restrict abusive words, first make an Array and store all the abusive words in that.
then in textView shouldChangeTextInRange: check whenever user press " space.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if([string isEqualToString:#" "])
{
//now iterate the whole string and find whether any word contains any value from your Abusive words Array and replace the word with blank space or *
}

How to avoid alphabet and special characters in a UITextfield?

I am formatting a US mobile number in a UITextfield.
I was done displaying the US number format, but it allows alphabet and special characters, including symbols.
I don't want allow alphabet and special characters.
How can I avoid these unwanted characters?
Please give any examples.
Try this
#define ACCEPTABLE_CHARACTERS #" Replace with what you want to be allowed."
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];
return [string isEqualToString:filtered];
}
Please refer below link which fulfills your requirement of displaying and accepting only numeric values in UITextFiled -
http://hugolarcher.com/uitextfield-allowing-only-decimal-characters/

using rangeOfString and textfield shouldChangeCharactersInRange - the delete character?

I'm using rangeofString and textfield: shouldChangeCharactersinRange: to restrict the types of keystrokes that will be valid in a textfield.
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *includeString = #"1234567890-()+" ;
if ([includeString rangeOfString:string].location == NSNotFound) {
return NO;
}
return YES;
}
this works fine EXCEPT i now can't use the delete key. Any ideas how to represent the delete key to add it to the includeString?
I tried
`NSString *includeString = #"1234567890-()+\b"
but that didn't work - neither did it allow the \ or b characters to appear which i thought odd
Thanks
The replacement string string is empty when characters are deleted.
Since rangeOfString:string returns NSNotFound for an empty string,
you have to check for that situation first:
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string length] == 0)
return YES;
NSString *includeString = #"1234567890-()+" ;
if ([includeString rangeOfString:string].location == NSNotFound) {
return NO;
}
return YES;
}
Update: As #rmaddy correctly pointed out, the above method fails if more than one
character is pasted into the text field. The following method checks if all
characters of the replacement string are valid. (There are probably many solutions,
this is only one of them.)
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
static NSString *includeString = #"1234567890-()+";
NSCharacterSet *includeSet = [NSCharacterSet characterSetWithCharactersInString:includeString];
if ([[string stringByTrimmingCharactersInSet:includeSet] length] > 0)
return NO;
return YES;
}
Note that the empty string does not need to be handled separately anymore.

Calling a method on every edit of UITextField

I'm now programming a simple app that has 3 UITextFields and if I edit one, the other two should scale together with it.
I tried using
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
this method, but:
replacement string is the last character that was typed in
can't figure out how backspace works there
it is being called a little too early
if I can "fix" the first point(by sending
[NSString stringWithFormat:#"%#%#", [textField text], string];
as a parameter), it will not "fix" the second point, because string variable is:
(lldb) po string
(NSString *) $1 = 0x0080cf14 <object returned empty description>
So the question is: is there any method that is being called AFTER textFieldShouldChangeCharactersInRange:? Or is there a way to:
return YES in textFieldShouldChangeCharactersInRange: method
and THEN call a method to change the values of the 2 other UITextFields?
EDIT
I could use the following:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
[self performSelector:#selector(myMethod:) withObject:textField afterDelay:0.1];
return YES;
}
but it doesn't seem to be the safest solution
The backspace works modifying the NSRange with a empty string. What you can do is modify the three text field in the textField:shouldChange and then return NO to the method.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string]; // this is what will happen if you return yes to this method
anotherTextField.text = // do whatever u need
yetAnotherTextField.text = // do whatever u need
return NO;
}
The following code prints correctly the full text of the text view (with the last character that was inserted), can that be useful?
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string length])
NSLog(#"Current Text:%#", [textField.text stringByAppendingString:string]);
else
NSLog(#"Current Text:%#", [textField.text substringWithRange:(NSRange){0, [textField.text length]-1}]);
return YES;
}
The backspace just sends an empty string in the string parameter.
For textFields:
[yourtextField addTarget:self action:#selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange
{
//Your Code
}

Resources