метод проверки текстового поля obj c - PullRequest
1 голос
/ 12 февраля 2020

У меня есть представление с 2 полями текстовых полей и кнопкой.

в функции "clickOnDoneButton". Мне нужно выполнить следующую функцию: я должен убедиться, что вывод вставлен в первое текстовое поле со вторым текстовое поле. Я должен проверить контакт с помощью функции «checkValidityPin», которая является правильной, я не могу правильно ее реализовать. логика c, которую нужно реализовать: я проверяю первый «пин», введенный с помощью checkValidityPin, если он правильный, я проверяю его вторым «пин», который должен быть таким же.

Я думаю, что получил потерял в функции больше не могу go на ..

    @property (nonatomic, strong) id delegate;
@property (nonatomic, weak) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet InputTextView *insertPin;
@property (weak, nonatomic) IBOutlet InputTextView *verifyPin;
@property (nonatomic, strong) NSString* stringInserted;

- (IBAction) clickOnDoneButton:(id)sender;


- (IBAction) clickOnDoneButton:(id)sender{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            NSString * errorMessage = @"";

            if(!self.insertPin || [self.insertPin isEqual:[NSString string]]) {
                self.insertPin = self.stringInserted;
//                [self.insertPin redrawWithInputLength:0];
    //            self.titleLabel.text = NSLocalizedString(@"INSERT_NEW_PIN", nil);
//                [self setTextAnimated:NSLocalizedString(@"INSERT_NEW_PIN", nil)];
//                self.keyboard.confirButton.enabled = NO;
                self.stringInserted = [NSString string];
            } else if(!self.verifyPin || [self.verifyPin isEqual:[NSString string]]) {
                if (![self.stringInserted isEqualToString:self.insertPin]){
                    if([self checkValidityPin:self.stringInserted]){
                        self.verifyPin = _stringInserted;

//                        [self.fieldView redrawWithInputLength:0];
    //                    self.titleLabel.text = NSLocalizedString(@"REINSERT_NEW_PIN", nil);
//                        [self setTextAnimated:NSLocalizedString(@"REINSERT_NEW_PIN", nil)];
//                        self.keyboard.confirButton.enabled = NO;
                        self.stringInserted = [NSString string];
                        NSLog(@"TEST4");
                    }
                    else{
                        errorMessage = NSLocalizedString(@"WRONG_PIN_FORMAT", nil);
                        NSLog(@"TEST2");

                    }
                } else {
                    errorMessage = NSLocalizedString(@"NEW_PIN_EQUALS_OLD", nil);
                    NSLog(@"TEST3");

                }
            }

            else if([self.verifyPin isEqual:self.stringInserted]) {
                NSLog(@"TEST");
            }
            else {
//                [self.fieldView redrawWithInputLength:0];
                self.stringInserted = [NSString string];
                self.insertPin = nil;
                self.verifyPin = nil;
                NSLog(@"TEST1");

//                [self setTextAnimated:NSLocalizedString(@"INSERT_OLD_PIN", nil)];
                //            self.keyboard.confirButton.enabled = NO;
                errorMessage = NSLocalizedString(@"PIN_NOT_EQUALS", nil);
            }

            //Show Error
//            if([errorMessage length]>0){
//                [self showError:errorMessage];
//            }

        }];
}

-(BOOL) checkValidityPin:(NSString*)pin{
    NSString *regex1 = @"^(01234|12345|23456|34567|45678|56789)$";
    NSString *regex2 = @"^(98765|87654|76543|65432|54321|43210)$";
    NSString *regex3 = @"^([0-9])\\1*$";

    BOOL testPassed1 = [PRUtility validateRegularExpression:regex1 forString:pin];
    BOOL testPassed2 = [PRUtility validateRegularExpression:regex2 forString:pin];
    BOOL testPassed3 = [PRUtility validateRegularExpression:regex3 forString:pin];

    return !(testPassed1 || testPassed2 || testPassed3);
}

1 Ответ

0 голосов
/ 12 февраля 2020

Легко потеряться, если вы только пишете код. Попробуйте сначала написать это «простым языком», а затем введите код.

Например:

  1. получить каждую введенную строку

  2. введенный пин-код пуст? Если это так, сообщите пользователю (обновите пользовательский интерфейс) и не беспокойтесь о какой-либо другой проверке.

  3. - одинаковые ли введенные строки? Если нет, сообщите об этом пользователю (обновите пользовательский интерфейс) и не беспокойтесь о других проверках.

  4. строки совпадают, поэтому проверьте введенный пин

  5. Пин в правильном формате? Если нет, сообщите об этом пользователю (обновите пользовательский интерфейс) и больше ничего не беспокойтесь.

  6. штырьки совпадают и были проверены, поэтому перейдите к следующему шагу

Вот с заполненным кодом:

- (IBAction)clickOnDoneButton:(id)sender {

    // 1. get each entered string
    NSString *insertPinString = [_insertPin text];
    NSString *verifyPinString = [_verifyPin text];

    // 2. is the entered pin empty?
    if ([insertPinString length] == 0) {
        // inform user he didn't enter a pin
        // update error label or show alert, whatever

        NSLog(@"No Pin Entered");

        // don't bother with anything else
        return;
    }

    // 3. are both entered strings the same?
    if (![insertPinString isEqualToString:verifyPinString]) {
        // inform user the pins don't match
        // update error label or show alert, whatever

        // probably clear both fields
        _insertPin.text = _verifyPin.text = @"";

        NSLog(@"Pin Mismatch");

        // don't bother with anything else
        return;
    }

    // 4. strings are the same, so validate entered pin
    BOOL bValid = [self checkValidityPin:insertPinString];

    // 5. if invalid pin entered
    if (!bValid) {
        // inform user it's an invalid pin format
        // update error label or show alert, whatever

        // probably clear both fields
        _insertPin.text = _verifyPin.text = @"";

        NSLog(@"Invalid Pin");

        // don't bother with anything else
        return;
    }

    // 6. pins match and have been validated so we can proceed with next step
    NSLog(@"Successful pin entry!");

}
...