9

I am writing validation for my textfield, I found something interesting that whether I can check how many digits I am typing into the textfield at real time. My text field input must be 8 digit number. So I want to change the text inside the text field to green colour when I reach 8 digit and change colour when it's not.

How can I do that? Please help me, thanks in advance.

Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
user1035877
  • 249
  • 1
  • 5
  • 15

7 Answers7

25

Using -textField:shouldChangeCharactersInRange:replacementString: is probably a bad solution because it fires before the text field updates. This method should probably be used when you want to change the text of the text field before the keyboard automatically updates it. Here, you probably want to simply use target-action pairing when editing value changes:

[textField addTarget:self action:@selector(checkTextField:) forControlEvents:UIControlEventEditingChanged];

Then, in - (void)checkTextField:(id)sender, try this:

UITextField *textField = (UITextField *)sender;
if ([textField.text length] == 8) {
    textField.textColor = [UIColor greenColor]; // No cargo-culting please, this color is very ugly...
} else {
    textField.textColor = [UIColor blackColor];
    /* Must be done in case the user deletes a key after adding 8 digits,
       or adds a ninth digit */
}
aopsfan
  • 2,451
  • 19
  • 30
4
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];

//    [textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
    NSLog(@"%@",searchStr);
    return YES;
}
btmanikandan
  • 1,923
  • 2
  • 25
  • 45
3

Use UITextFieldDelegate. especially this function

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

and you can get sample codes links from here..

Community
  • 1
  • 1
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
  • 1
    The accepted solution is better because as @aopsfan mentions: `Using -textField:shouldChangeCharactersInRange:replacementString: is probably a bad solution because it fires before the text field updates.` Thus, you lose the "real-time" requirement and the updates are one character behind (off-by-one). – Tom Redman Apr 20 '12 at 14:41
  • No this is the correct approach. Getting a string processed to replicate the future version of the string is simple. Also, Apple in their documentation suggests using this for realtime checks and validation. – Johan Jan 30 '19 at 14:15
2
[textField addTarget:self action:@selector(checkTextField) forControlEvents:UIControlEventEditingChanged];

Try it!

Kaijay Lu
  • 114
  • 3
1

Set up a delegate for the UITextField and implement the method – textField:shouldChangeCharactersInRange:replacementString: Details and examples are in the UITextFieldDelegate Protocol Reference, but here's a quick example:

- (BOOL)textField:(UITextField *)textField 
shouldChangeCharactersInRange:(NSRange)range 
replacementString:(NSString *)string
{
        NSString *text = [textField text];
        // NOT BACKSPACE
        if ([string length] || text.length + string.length < 8) {
            return YES;
        } else if (text.length + string.length > 8) {
            return NO;
        } else {
                // DO SOMETHING FOR LENGTH == 8
                return YES;
        }
}   
PengOne
  • 48,188
  • 17
  • 130
  • 149
0

Update Swift 4.0

 txtFieldAdd.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

Now call your function. In my case, this will enable the save button

@objc func textFieldDidChange(_ textField: UITextField) {
    if (txtFieldAdd.text?.isEmpty)! {
        btnSave.isEnabled = false
    }
    else {
        btnSave.isEnabled = true
    }
}

Hope it helps.

Harjot Singh
  • 6,767
  • 2
  • 38
  • 34
0

This is how you get realtime validation without setting up anything other than the delegate of the textfield:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Creating the future string. The incoming string can be a single character,
    // empty (on delete) or many characters when the user is pasting text.

    let futureString: String = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string)

    // Determine if the change is allowed, update form, etc.
    let allowChange = <#Your Validation Code#>

    return allowChange
}

Add this code to the designated delegate of the textfield. Simple.

Johan
  • 2,472
  • 1
  • 23
  • 25