Validate Textfield after each character entered

2020-08-04 04:20发布

问题:

I have searched for an answer but cant find an answer related to this.

I am trying to validate every input into a textfield but not sure how to go about it, the idea is to check a username exist on a server so I would assume I need to post to the server each time something is entered and if success do whatever.

Could someone please advise I would be grateful.

回答1:

You can use addTarget:action:forControlEvents: with UIControlEventValueChanged (e.g: [textfield addTarget:self action:@selector(usernameChanged:) forControlEvents:UIControlEventValueChanged). This will inform you AFTER the text changes (so when you receive usernameChanged: you'll have the last modifications).

It's probably a good idea that instead of sending a request to the server each time the username changes you either send a request when the textfield looses caption or when some time passes from the last change (you can use a NSTimer for this).

You should use a single asynchronous request. If the request is active and the textfield is edited again you should cancel the request and set it to nil (since there's no reason to check the old username). If the request succeeds show up an icon, or whatever you want to do when you get the result from the server.

Edit: Not sure if UIControlEventValueChanged worked on previous versions of iOS or if it was a mistake from my side, but it doesn't seem to work any longer. UIControlEventEditingChanged should be used instead.



回答2:

Implement the delegate method textField:shouldChangeCharactersInRange:replacementString: to be informed about every change to the text. Return YES or NO depending on whether you want to accept the change or not.

It is probably a very bad idea to ask the server for approval of every single key press since that would create an intolerable lag and lead to a very bad user experience.



回答3:

What Ole is saying is absolutely correct. I'll just give you an example of what he's saying.

First conform your class to the UITextFieldDelegate protocol. Then make sure in viewDidLoad (or similar) that you set the delegate to your class:

myTextField.delegate = self;

Next you can implement the method that Ole was mentioning. However, in your case you're not validating whether the user can enter anything or not, you just want to know what he entered so you can validate it online.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    [self verifyTheUserWithUsername:[textField.text stringByReplacingCharactersInRange:range withString:string]];
    //do your appropriate check here
    return YES; //we allow the user to enter anything
}