UITextfiled验证1-100之间的国家货币



如何验证UITextfield的货币值在1到100之间,最多可接受2个十进制值。

有效。0.25 99.99,1.99100.00。其他国家货币十进制表示。0.2599,991,99100000

无效00.25、100.25、0000000.00、0.125、9.567

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
numberFormatter.locale = [NSLocale currentLocale];// this ensures the right separator behavior
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
numberFormatter.usesGroupingSeparator = YES;
numberFormatter.usesSignificantDigits = YES;
numberFormatter.currencyGroupingSeparator = numberFormatter.locale.groupingSeparator;
numberFormatter.decimalSeparator = numberFormatter.locale.decimalSeparator;
NSString *expression = @"^([0-9]+)?(\.,([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
 options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0 range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;

无法工作无法按下,在UITextfield中。瑞典货币十进制表示","不是"。"我要计算两个输入值,一个是int,另一个是float

在UItTxtfield委托方法中尝试以下代码。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSInteger Currency = [textField.text integerValue];
if(Currency >= 100)
{
return NO;
}
else
{
NSString *enteredCurrency=textField.text;
if([enteredCurrency containsString:@"."])
{
NSArray *array=[enteredCurrency componentsSeparatedByString:@"."];
if([array[1] length] >= 2 || [array[0] length] >= 2)
{
return NO;
}
else
{
return YES;
}
}
else
{
return YES;
}
}
}     

不建议您的lsef实现此功能,因为它不可扩展。您需要使用NumberFormatter(或用于ObjC的NSNumberFormatter(

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
formatter.allowsFloats = false
formatter.maximumFractionDigits = 2  //you get to control how to present the price.
formatter.locale = locale //This should be the country Locale you need. for example: "en-us"

请注意,NSLocale还允许您访问分组分隔符和小数分隔符,因此如果您愿意,可以稍后进行检查。

formatter.currencyGroupingSeparator = locale.groupingSeparator formatter.decimalSeparator = locale.decimalSeparator

最新更新