swift:
// MARK: - 判断字符串是否符合标准
extension String {
/// 根据设置个数判断 数字是否有通过
/// - Parameter textF: 输入框
/// - Parameter range: 输入位置
/// - Parameter importStr: 输入字符
/// - Parameter prePointCount: 小数点前个数(默认9)
/// - Parameter behindPointCount: 小数点后个数(默认2)
func checkTextF(textF: UITextField, changeCharactersInRange range: NSRange, importStr: String, prePointCount: Int = 9, behindPointCount: Int = 2) -> Bool {
if importStr.isEmpty == true {
return true
}
if textF.text?.contains(".") == true { // 只能输入一个.
if importStr == "." {
return false
}
if textF.text?.length ?? 0 >= prePointCount + behindPointCount + 1 {
log("没有小数点 不能输入超过限额")
return false
}
// 判断小数点位数
guard let ran = textF.text?.range(of: ".") else { return false}
guard let ran1 = textF.text?.toNSRange(ran) else { return false}
if range.location > ran1.location {//小数点后边输入
if (textF.text?.length ?? 0) - ran1.location == behindPointCount + 1 {
return false
}
return true
}else {//小数点前边输入
if (textF.text?.length ?? 0) >= prePointCount + behindPointCount + 1 {
log("没有小数点 不能输入超过限额 ");
return false
}
return true
}
}else {//无小数
if textF.text?.length ?? 0 >= prePointCount {
if importStr == "." {
return true
}
if importStr == "" {
return true
}
return false
}
}
if textF.text == "0" {//0后面只能输入.
return importStr == "." ? true : false
}
if importStr == " " {
return false
}
return true
}
}
OC:
/**
根据设置个数判断 数字是否有通过
@param textField 输入框
@param range 输入位置
@param string 输入字符
@param prePointCount 小数点前个数
@param behindPointCount 小数点后个数
@return 是否通过
*/
+(BOOL )checkTextF:(UITextField *)textField ChangeCharactersInRange:(NSRange)range importStr:(NSString *)string prePointCount:(NSInteger )prePointCount behindPointCount:(NSInteger )behindPointCount{
if ([string isEqualToString:@""]) {
return YES;
}
if ([textField.text containsString:@"."]) {//只能输入一个.
if ([string isEqualToString:@"."]) {
return NO;
}
if (textField.text.length >= prePointCount + behindPointCount + 1) {
NSLog(@"没有小数点 不能输入超过 123456.123456 ");
return NO;
}
//判断小数点的位数
NSRange ran = [textField.text rangeOfString:@"."];
NSLog(@"ran.location : %ld,range.location : %ld",ran.location,range.location);
if (range.location > ran.location) {//小数点后边输入
if (textField.text.length - ran.location == behindPointCount + 1) {
return NO;
}
return YES;
}else{//小数点前边输入
if (textField.text.length >= prePointCount + behindPointCount +1) {
NSLog(@"没有小数点 不能输入超过 10 0000 ");
return NO;
}
return YES;
}
}else{//无小数
if (textField.text.length >= prePointCount) {
if ([string isEqualToString:@"."]) {
return YES;
}
if ([string isEqualToString:@""]) {
return YES;
}
return NO;
}
}
if ([textField.text isEqualToString:@"0"]) {//0后面只能输入.
if ([string isEqualToString:@"."]) {
return YES;
}else{
return NO;
}
}
if ([string isEqualToString:@" "]) {
return NO;
}
return YES;
}