Sajith K
Sajith K

Reputation: 11

Form validation in Objective C

I am creating a signup page. The page has the following textfields FirstName, LastName, Gender, Email, Phone, Password and Confirm_Password. Before the signup I need to validate the fields. First I'm going to check whether any of the fields are empty. If any of the fields are empty, it should display a message. I have the following code. I know the code is simple and too lengthy. My question is how we can write the same functionality by reducing the code? How can we write the same code in a standard way?

 if([FirstName.text isEqualToString:@""])
{
    NSLog(@"FirstName should not be empty");
}
else if ([LasttName.text isEqualToString:@""])
{
   NSLog(@"LastName should not be empty");
}
else if ([Gender.text isEqualToString:@""])
{
    NSLog(@"Gender should not be empty");
}
else if ([Email.text isEqualToString:@""])
{
     NSLog(@"Email should not be empty");
}
else if ([Phone.text isEqualToString:@""])
{
     NSLog(@"Phone should not be empty");
}
else if ([Password.text isEqualToString:@""])
{
     NSLog(@"Password should not be empty");
}
else if ([Confirm_Password.text isEqualToString:@""])
{
     NSLog(@"Confirm_Password should not be empty");
}
else{
    NSLog(@"Signup Successful");
}

Upvotes: 1

Views: 2082

Answers (4)

dirtydanee
dirtydanee

Reputation: 6151

Here is a sample code for @norders answer:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

// Delcare IBOutletCollection in the header file
@property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *fields;

@end

Connect your textfields to your outlet:

enter image description here

Now do the following in your ViewController.m:

- (void) viewDidLoad {
    [super viewDidLoad];
    // Define placeholders - make sure you insert the placeholders in the same order as you place you textfields into the collection
    NSArray<NSString *>* placeholders = @[@"First name", @"Last name"]; 
    // Setting up the placeholders
    for (int i = 0; i < placeholders.count; i++) {
        UITextField* field = self.fields[i];
        NSString* placeholder = placeholders[i];
        field.placeholder = placeholder;
    }
}

- (IBAction)didPressValidate:(UIButton*)sender {
    [self validate:self.fields];
}

// Function to be called upon validation
- (void)validate:(NSArray<UITextField *>*)labels {
    NSMutableArray<UITextField *>* invalidFields = [NSMutableArray new];
    for (UITextField* field in self.fields) {
        if ([field.text isEqualToString:@""]) {
            [invalidFields addObject:field];
        }
    }
    [self displayWarningForInvalidLabesIfNeeded: invalidFields];
}

// Function to be called to show the error message
- (void)displayWarningForInvalidLabesIfNeeded:(NSArray<UITextField *>*)invalidFields {
    if ([invalidFields count] == 0) {
        // All labels are valid, no need for error message
        return;
    }

    NSMutableString* invalidFieldsMessage = [NSMutableString new];
    // Create string from invalid fields placeholder
    for (UITextField* field in invalidFields) {
        [invalidFieldsMessage appendString: field.placeholder];
        [invalidFieldsMessage appendString: @"\n"];
    }

    // Show the alert with the invalid fields
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Invalid fields" message:invalidFieldsMessage preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // code for handling when user pressed OK
        NSLog(@"ok pressed");
    }];

    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

And the end result should be like this: enter image description here

Upvotes: 4

Annie Gupta
Annie Gupta

Reputation: 2822

You can assign the tags to textFields and then use the switch case as below

- (void) emptyTextfieldValidation :(UITextField*) textfield {
    if ([textfield.text isEqualToString:@""]) {

        switch (textfield.tag) {
            case 101: NSLog(@"firstName should not be empty");
                break;
            case 102: NSLog(@"LastName should not be empty");
                break;
            case 103: NSLog(@"Gender should not be empty");
                break;
            case 104: NSLog(@"Email should not be empty");
                break;
            case 105: NSLog(@"Phone should not be empty");
                break;
            case 106: NSLog(@"Password should not be empty");
                break;
            case 107: NSLog(@"Confirm_Password should not be empty");
                break;

            default:
                break;
        }
    }

Upvotes: 0

Harshil
Harshil

Reputation: 209

You could use regular expressions to validate different textfields according to validation requirements.

Hope this will help you!

Upvotes: 0

norders
norders

Reputation: 1252

  1. In Interface Builder add all your text fields to an IBOutletCollection. This is just an array of interface objects, in your case UITextFields.
  2. Ensure you have the placeholder text field set that describes the content of the field.
  3. In your code, iterate the array of text fields and when you find an empty one add its placeholder text to a mutable array.
  4. Log the content of the mutable array to a pop-up dialog.

This way you can validate the entire form in a single small loop.

Upvotes: 2

Related Questions