2011-01-12 38 views
2

我在我的應用程序中有4個文本字段。如何驗證允許的文本字段。只有一次在文本域

驗證我的文本框的文本框爲允許0,1,...9.,對於我寫的代碼作爲休耕

- (IBAction) textfield:(id)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

但它不會允許一旦我放置。 ,那textfield不會被允許。

ed:123.45678。

我該怎麼做,

任何人都可以幫助我。

謝謝你提前。

+0

Mahesh能否讓這個問題更清楚。它很難說清楚你的要求。 – Robin 2011-01-12 06:33:06

回答

4

試試這個斷言對於文本與一些像 「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]]; 
啓動

如果你想允許「。」在拳頭地方,如」 0.95" 使用下面的正則表達式,

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

您的代碼應該是這樣的,

- (IBAction)textfield:(id)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] 
     } 
    } 
} 

我想這應該工作!試一試!

+0

我可以放置這個 – MaheshBabu 2011-01-12 06:54:16

0

那麼你可以使用此方法

- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet options:(NSStringCompareOptions)mask range:(NSRange)aRange

上的TextField.text

爲一個的NSString只

相關問題