imbeginner_sorry imbeginner_sorry - 1 year ago 92
iOS Question

How to check the textFiled input string when user inputting

I have a problem.

I have four textfields, but I don't know how to check the textfield that input String.

  • nameField
    doesn't over 10 strings

  • ageField
    check whether is number or not

  • sexField
    check male or female

This is my code:

- (IBAction)addComment:(id)sender {

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Commend" message:nil preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Please input your name:";
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Please input your age:";
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Please input your sex:";
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Please input your commend:";

UIAlertAction *sendAction = [UIAlertAction actionWithTitle:@"send" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

UITextField *nameField = alertController.textFields[0];
UITextField *ageField = alertController.textFields[1];
UITextField *sexField = alertController.textFields[2];
UITextField *commentField = alertController.textFields[3];

UIAlertController *successAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Success" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

[self.navigationController popViewControllerAnimated:YES];

[successAlertController addAction:okAction];
[self presentViewController:successAlertController animated:YES completion:nil];


[alertController addAction:sendAction];
[self presentViewController:alertController animated:YES completion:nil];



Answer Source

Follow below steps, may it help:

  1. Set delegate and tag to UIAlertController textfields.

  2. Now use UITextField delegate method shouldChangeCharactersInRange to validate text while typing OR use textFieldDidEndEditing to check after textfield end editing . Check using it's tag to differentiate between textFields.


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


   //Validate Name textField
//Same way for other textFields

    return YES; 

OR Use textFieldDidEndEditing to validate while textField end editing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download