OGeek|极客世界-中国程序员成长平台

标题: iphone - 如何验证允许 .在文本字段中只有一次 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:45
标题: iphone - 如何验证允许 .在文本字段中只有一次

我的应用程序中有 4 个文本字段。

我将我的文本字段验证为文本字段允许 0,1,...9.,因为我将代码编写为休闲

- (IBAction) textfieldid)sender {

    if ([textfield.text length] > 0) {
        if ([textfield.text length] > 10){          
            textfield.text = [textfield.text substringWithRange:NSMakeRange(0, 10)];
    }
        else {
            //retrieve last character input from texfield           
            int I01 = [homevalue.text length];
            int Char01 = [homevalue.text characterAtIndex:I01-1];
            //check and accept input if last character is a number from 0 to 9
            if ( (Char01 < 46) || (Char01 > 57) || (Char01 == 47) ) {

                if (I01 == 1) {
                    textfield.text = nil;
                }
                else {

                    textfield.text = [homevalue.text substringWithRange:NSMakeRange(0, I01-1)];
                }
            }

        }
    }

} 

它工作正常,现在我需要验证 . 只允许在文本字段中使用一次。

例如:123.45

根据我的代码,如果我再次放置 . 是允许的。 例如:123.45.678

但是一旦我放置它就不允许了。 ,该文本字段是不允许的。

编辑:123.45678。

我该怎么做呢,

谁能帮帮我。

提前谢谢你。



Best Answer-推荐答案


对以“23.67”等数字开头的文本试试这个谓词

NSString *decimalRegex = @"[0-9]+([.]([0-9]+)?)?"; // @"[0-9]+[.][0-9]+";
NSPredicate *decimalTest = [NSPredicate predicateWithFormat"SELF MATCHES %@", decimalRegex]; 
BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];

如果你想允许“。”在“.95”之类的第一个位置使用以下正则表达式,

NSString *decimalRegex = @"[0-9]*([.]([0-9]+)?)?"; //@"[0-9]*[.][0-9]+";

您的代码应如下所示,

- (IBAction)textfieldid)sender {

    int textLength = [[textfield text] length];

    if (textLength > 0) {

        NSString *decimalRegex = @"[0-9]+([.]([0-9]+)?)?"; //@"[0-9]+[.][0-9]+";
        NSPredicate *decimalTest = [NSPredicate predicateWithFormat"SELF MATCHES %@", decimalRegex]; 
        BOOL isValidDecimal = [decimalTest evaluateWithObject:[textField text]];

        if (!isValidDecimal) {

            NSString *text = [[textField text] substringToIndex:textLength - 1];
            [textfield setText:text] 
        }
    } 
}

我想这应该可行!试试看!

关于iphone - 如何验证允许 .在文本字段中只有一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665884/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4