• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iphone - 如何验证允许 .在文本字段中只有一次

[复制链接]
菜鸟教程小白 发表于 2022-12-12 15:45:38 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我的应用程序中有 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap