使用正则表达式的TextField验证 [英] TextField Validation With Regular Expression

查看:162
本文介绍了使用正则表达式的TextField验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助看看文本字段的代码,确保它以(+或 - )开头,然后有3个整数。

I need help with code that looks at a textfield make sure it starts with either a (+ or -) then has 3 integers after it.

所以有效的数据看起来像+234或-888

So valid data looks like +234 or -888

所以我开始这个代码,但有2

So I have started this code but there are 2 problems with it


  1. 它正确验证只输入4个字符。但是由于某些原因,你必须从文本框中取出焦点,以便键盘上的完成按钮启动和隐藏键盘。如果我只把少于4个字符在文本字段,然后完成按钮工作正常。但我不希望用户输入除4个字符以外的任何内容,然后按完成并隐藏键盘。这是第一个问题....

  1. It correctly validates that only 4 characters are entered. But for some reason you have to take focus off the textfield in order for the Done button on the keyboard to fire and hide the keyboard. If I only put less than 4 characters in the textfield then the Done button works fine. But I dont want the user to enter anything but 4 characters and then press Done and hide the keyboard. Thats the first problem....

我不熟悉正则表达式以及如何在iphone中使用它们。因此,我需要为上述要求添加到此代码正则表达式。

I am not familar with regular expressions and how to use them in iphone. So I need to add to this code regular expression for the above requirement.

-(BOOL)textField:(UITextField*)textFieldshouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
     return !([newString length] > 4);
}
//Done button to hide the keyboard
-(IBAction)Done:(id)sender
{

}



推荐答案

如何处理用户输入和反馈。首先,我将展示一个简单的方法来保持用户在textField的编辑模式,如果她的输入无效。

I am not sure how you'd like to handle user input and feedback. First I'll show a simple way to keep the user in the editing mode of the textField if her input is not valid.

首先,两个委托方法:

- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
    [aTextField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)aTextField
{
    return [self validateInputWithString:aTextField.text];
}

测试方法,只返回YES或NO,是否有效:

- (BOOL)validateInputWithString:(NSString *)aString
{
    NSString * const regularExpression = @"^([+-]{1})([0-9]{3})$";
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regularExpression
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error) {
        NSLog(@"error %@", error);
    }

    NSUInteger numberOfMatches = [regex numberOfMatchesInString:aString
                                                        options:0
                                                          range:NSMakeRange(0, [aString length])];
    return numberOfMatches > 0;
}

就是这样。但是,我建议向用户显示一些实时状态,无论他的输入是否正确。添加以下通知,例如在您的viewDidLoad方法中:

That's it. However I'd recommend showing some live status to the user whether his input is ok or not. Add the following notifcation, for example in your viewDidLoad method:

- (void)viewDidLoad
{
    // ...
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(validateInputCallback:) 
                                                 name:@"UITextFieldTextDidChangeNotification" 
                                               object:nil];
}

- (void)validateInputCallback:(id)sender
{
    if ([self validateInputWithString:textField.text]) {
        // For example turn a label green and let it say: "OK"
    } else {
        // For example turn a label red and let it say: "Allowed: + or minus followed by exactly three digits"
    }
}

最后:需要访问正则表达式的捕获组(+或 - 和数字),以下代码将有助于:

Finally: If you need to access the capture groups (+ or - and the number) of the regular expression the following code will help:

// ... reg ex creation ...
NSArray *matches = [regex matchesInString:aString
                                  options:0
                                    range:NSMakeRange(0, [aString length])];

for (NSTextCheckingResult *match in matches) {
    for (int i = 0; i < [match numberOfRanges]; i++) {
        NSLog(@"range %d: %d %d", i, [match rangeAtIndex:i].location, [match rangeAtIndex:i].length);
        NSLog(@"substring %d: %@", i, [aString substringWithRange:[match rangeAtIndex:i]]);
    }
}

这篇关于使用正则表达式的TextField验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆