使用正则表达式验证文本字段 [英] TextField Validation With Regular Expression

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

问题描述

我需要有关查看文本字段的代码的帮助,确保它以 (+ 或 -) 开头,然后有 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

所以我已经启动了这段代码,但它有两个问题

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]]);
    }
}

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

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