您好我正在使用以下代码,所以我的系统只验证要输入到我的文本框中的数字,这很好。然而,我刚刚在一个文本字段上实现了ii将需要它只验证0.5到24之间的数字,可能使用正则表达式,即使弄清楚如何获得正则表达式正确的如何将其包含到函数中,这个绊脚石也是如此只允许数字,只允许从.5到24的数字。基本上人们可以选择在一天中使用30分钟到24小时之间的设备,任何保留为0的字段都会导致错误。
我试图在这里做的是陷阱textfield2这是要设置为最大24的字段。我遇到的问题是如何限制数量,如果ic陷阱,我该如何将其返回
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// First, create the text that will end up in the input field if you'll return YES:
if (textField == textField2) { }
NSString *resultString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* resultingNumber = [numberFormatter numberFromString:resultString];
//[numberFormatter release];
return resultingNumber != nil;
}
答案 0 :(得分:1)
使用此正则表达式(^([1] [0-9] | [2] [0-4] |(0?)[1-9])((。[0-9] )|)| 0 [。] [5-9] [0-9] $)验证0.5到24之间的数字..
答案 1 :(得分:0)
我最近做过类似的事情,但会尝试根据你的情况调整它。如果我哄骗了一行代码,在给我翻新之前给我打电话......已经很晚了;)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSError *error = NULL;
//check for text being pasted vs valid decimal
//below regex will check for a decimal number with a precision of 2
NSRegularExpression *regexNumeric = [[NSRegularExpression alloc]initWithPattern:@"^([0-9]+)?(\\.([0-9]{1,2})?)?$" options:NSRegularExpressionCaseInsensitive error:&error];
if ([regexNumeric numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])] > 0)
{
//found a valid entry
switch ([string length])
case 0:
case 1:
{
//this is always a valid entry since the field is either empty or 0-9 or .
return YES;
break;
}
case 2:
{
//Need to handle whole numbers, decimals starting with ".", and a decimal starting with "0." which is valid
if ((([string floatValue] <= 24.0) && ([string floatValue] >= 0.5)) || ([string isEqualToString:@"0."]))
{
return YES;
}
else
{
return NO;
}
break;
}
case 3:
case 4:
case 5:
{
//will handle all other cases
if (([string floatValue] <= 24.0) && ([string floatValue] >= 0.5))
{
return YES;
}
else
{
return NO;
}
break;
}
default:
{
//no idea how you got here!
return NO;
}
}
else
{
return NO;
}
}
答案 2 :(得分:0)
if(num2 == 0 || num1&lt; = 0.000 || num3 == 0 || num4 == 0 || dnumb == 0 || num2&gt; 24){在完整的代码不同部分,它拉起了一个消息框,我需要的验证就是在这里完成,不需要正则表达式, - Imran Raja昨天