用于货币验证的Objective C正则表达式

时间:2015-04-27 07:43:50

标签: ios objective-c regex uitextfield

我有一个金额的输入字段,其中应该允许用户输入最小值Rs.10和最大值Rs.99999,即输入字符串的长度范围在2到5之间。我希望有一个检查如果用户输入了无效的数字eq 01,002,9999999,030。这些都是无效的,不应该被接受。

以下是我的示例代码:

if ([amount.text length]>=2 && [amount.text length]<=5) {
}
else {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:@"Plz enter the amout Min 10Rs" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    return;
}

4 个答案:

答案 0 :(得分:1)

或者,您可以使用^[1-9][0-9]{1,4}$正则表达式检查此值:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[1-9][0-9]{1,4}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSRange textRange = NSMakeRange(0, amount.text.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:amount.text options:NSMatchingReportProgress range:textRange];
// Did we find a match?
if (matchRange.location != NSNotFound)
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:@"Plz enter the amout Min 10Rs" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    return;
 }

答案 1 :(得分:0)

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
              if ([amount.text length]>=2 && [amount.text length]<=5) 
    {
    }
     else
      {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"error" message:@"Plz enter the amout Min 10Rs" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
      }


}

试试这个

答案 2 :(得分:0)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
              if ([amount.text length]>=10 && [amount.text length]<=9999) 
    {
    }
     else
      {
        UIAlertView *alertdemo = [[UIAlertView alloc]initWithTitle:@"error" message:@"please enter the amount Min 10Rs and Max amount 9999" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertdemo show];
        return;
      }


}

答案 3 :(得分:0)

我认为您需要在textFieldDidEndEditing内执行验证。因为shouldChangeCharactersInRange每次改变角色时都会打电话。

- (void)textFieldDidEndEditing:(UITextField *)textField{

    if ([textField.text integerValue]<10 || [textField.text integerValue]>99999) {

        UIAlertView *alertdemo = [[UIAlertView alloc]initWithTitle:@"error" message:@"please enter the amount Min 10Rs and Max amount 9999" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertdemo show];
    }


}