add prefix to UITextField - ios

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.

Related

How do I enforce that an UITextView shows only lower-case letters? [duplicate]

This question already has answers here:
Converting all text to lower case in Objective-C
(3 answers)
Closed 7 years ago.
I'm working on a social script for iOS but i'll need my username login only be lowercase. I've got the string where lowercaseString needs to be into but I don't exactly know where.
So this is the code:
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];**
Where do I put the .lowercaseString for only lowercase login?
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;
However, this only ensures that username is lowercase. To make sure that the UITextField contains only lowercase characters, you may do this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSRange upperCharRange;
upperCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];
if (uppercaseCharRange.location != NSNotFound) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string lowercaseString]];
return NO;
}
return YES;
}
This method is only called if you add <UITextFieldDelegate> to the .h file of your class. You also need to set the delegate of your UITextField instance to self of your class instance, like so:
textField.delegate = (id <UITextFieldDelegate>)mainViewController;
You can put it after self.usernameField.text or after the ]]. There is not really any difference since lowerCase does not affect whitespaces or newline characters.
The only difference is that after trimming the string, the string might be shorter and therefore the transformation to a lower case string will take less time (not noticeably though).
Therefore I would propose adding it after ]]:
NSString *username = [self.usernameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].lowercaseString;

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

UITextField auto-delete

When a user holds down the delete key for a certain amount of time, the UITextField begins deleting multiple characters at once. I'm trying to create a UITextField that has a # as the first character. This # should never be deleted. The code below works to prevent the user from deleting the # accept when the user types in many characters, and then proceeds to hold down the delete key until UITextField deletes multiple characters at once. The user is then able to delete all characters from the UITextField despite the logic below. How can this be?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (newLength < 1)
return NO;
else if (newString.length == 0)
return NO;
return (newLength > 30) ? NO : YES;
}
Perhaps something like this would be better:
- (void) textViewDidChange:(UITextView *)textView {
if (![textView.text hasPrefix:#"#"]) {
textView.text = [NSString stringWithFormat:#"#%#", textView.text];
}
}
This way, at any point, if your text view doesn't have a '#' as a prefix, this puts one in. Otherwise, if the user types 10 characters, then goes back and erases the '#' the system won't recognize it, or if they highlight all of the text and erase it. If later code depends on the '#' char, I'd say this is probably more reliable.
I'm not sure if the shouldChangeCharactersInRange method is technically allowed to modify the text field directly, but give this a try and let me know how it goes.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ( newString.length > 30 )
return( NO );
if ( newString.length < 1 )
newString = #"#";
textField.text = newString; // I'll change the string myself thanks
return( NO ); // string's already changed, don't change it again
}

Restricting text input to only alpha characters

I have seen multiple approaches to this but cannot get this to work.
I am trying to restrict a text field to only allow alpha characters entered into it. I.e. ABCDEFabcdef (but all of them).
Here is my existing method:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Check for the back space/delete
if (string.length <=0 ) {
if ([self.wordArray lastObject]) {
[self.wordArray removeObjectsInRange:range];
[self.tileCollectionView reloadData];
return YES;
}
}
// Check to make sure the word is not above 16 characters, that should be enough right?
if (textField.text.length >= 16 ) {
NSLog(#"WOOO SLOW DOWN THE TEXT IS ABOVE 16");
return NO;
} else {
[self.wordArray addObject:string];
[self.tileCollectionView reloadData];
return YES;
}
}
At present I check for a back space and remove the last entry from an Array. Also if the letter is accepted then I add the letter as an object to an array, that is for something else. But the logic for the ALPHA check should also take this into account, only if the letter is 'legal' should it add to the array and reload the collection view.
Well, one way you could do it would be to create your own character set to compare against. Then you can take advantage of NSString's stringByTrimmingCharactersInSet: and NSCharacterSet's invertedSet property to remove all characters from the set that don't match the characters you initially specify. Then, if the final string matches the input string, it didn't contain illegal characters.
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSString *input = #"a";
NSString *output = [input stringByTrimmingCharactersInSet:[myCharSet invertedSet]];
BOOL isValid = [input isEqualToString:output];
NSLog(#"%d",isValid);

Objective-c How to do validation on textField

I would like to prevent the user from not entering any data as well as entering only spaces. So basically there must at least be one character without a space. Then I would also like to remove any spaces at the beginning of the word so the first letter is a character that is not a space.
edit
the user must enter something and if the user enters a few spaces before it then I want to trim those spaces. I also want to prevent the user from just entering spaces.
Example
if the user enter's a name and surname like " James Dean" I would like to take the first space away but not the second space between James and Dean.
Set your UIViewController to be your destination UITextField's delegate and implement this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// verify the text field you wanna validate
if (textField == _nameTextField) {
// do not allow the first character to be space | do not allow more than one space
if ([string isEqualToString:#" "]) {
if (!textField.text.length)
return NO;
if ([[textField.text stringByReplacingCharactersInRange:range withString:string] rangeOfString:#" "].length)
return NO;
}
// allow backspace
if ([textField.text stringByReplacingCharactersInRange:range withString:string].length < textField.text.length) {
return YES;
}
// in case you need to limit the max number of characters
if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 30) {
return NO;
}
// limit the input to only the stuff in this character set, so no emoji or cirylic or any other insane characters
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "];
if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
return NO;
}
}
return YES;
}
try like this may be it helps to you,here is my code
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string{
if([text.text length]==0){
if([string isEqualToString:#" "]){
return NO;
}
}
return YES;
}
By placing this code user won't enter space as a first letter but it accepts the space in the middle of the string.
I'll give you a hint for the first part.
NSString *tempname1 = [self.textField.text stringByReplacingOccurrencesOfString:#" " withString:#""];
BOOL thereAreJustSpaces = [tempname1 isEqualToString:#""];
-(void)removeSpacesFromTextFields:(id) sender {
NSString *trim = [self.FNTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([trim length] == 0) {
self.FNTextField.text = #"";
}
}
Try this, If you want to prevent space in your text field.
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(checkSpace:) name:UITextFieldTextDidChangeNotification object:textfield];
}
-(void)checkSpace:(NSNotification *)notification
{
str = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] ;
textfield.text=str;
}

Resources