/// 判断输入有效的金额开头
- (BOOL)isEnabelStartPriceWithReplaceText:(NSString *)replaceText
{
/// 如果只输入. 则变成0.
if ([self isEqualToString:@"."]) {
return NO;
}
/// 如果输入0则变成0.
if ([replaceText isEqualToString:@"0"] && [self isEqualToString:@"0"]) {
return NO;
}
return YES;
}
///判断是否为有效金额输入
- (BOOL)isValidPriceInput {
if (self.length == 0) return YES;
NSString *reg = @"^([1-9][0-9]{0,8}|[1-9][0-9]{0,8}\\.[0-9]{0,2}?|0|0\\.[0-9]{0,2}?)$";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
return [predicate evaluateWithObject:self];
}
使用示例
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
/// 1.如果只输入. 则变成0.
/// 2.如果只输入0则变成0.
if (![str isEnabelStartPriceWithReplaceText:string]) {
textField.text = @"0.";
return NO;
}
//匹配有效金额
if (!str.isValidPriceInput) {
return NO;
}
return YES;
}
网友评论