检查UITextField的输入是否仅为数字 [英] Check that a input to UITextField is numeric only

查看:113
本文介绍了检查UITextField的输入是否仅为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证 UITextField 的字符串输入?

How do I validate the string input to a UITextField? I want to check that the string is numeric, including decimal points.

推荐答案

我在Mac应用程式中使用这个程式码,或类似应该与iPhone一起工作。它是基于RegexKitLite正则表达式,并且当其无效时将文本变为红色。

I use this code in my Mac app, the same or similar should work with the iPhone. It's based on the RegexKitLite regular expressions and turns the text red when its invalid.

static bool TextIsValidValue( NSString* newText, double &value )
{
    bool result = false;

    if ( [newText isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"] ) {
        result = true;
        value = [newText doubleValue];
    }
    return result;
}

- (IBAction) doTextChanged:(id)sender;
{
    double value;
    if ( TextIsValidValue( [i_pause stringValue], value ) ) {
        [i_pause setTextColor:[NSColor blackColor]];
        // do something with the value
    } else {
        [i_pause setTextColor:[NSColor redColor]];
    }
}

这篇关于检查UITextField的输入是否仅为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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