How to Test Character Input to UITextField as the User Enters Characters and Prevent Invalid Characters

前端 未结 6 1920
深忆病人
深忆病人 2020-12-02 16:22

First, I setup up the keyboard for the UITextField to use the number with decimal style. So the user can only enter numbers and a single decimal.

What I want to do i

6条回答
  •  一生所求
    2020-12-02 16:40

    You can pass the string of uitexfield to below method, it will return yes/no..accordingly you can show error

    - (BOOL) validatePhone: (NSString *) aMobile {
        NSString *phoneRegex = @"^+(?:[0-9] ?){6,14}[0-9]$"; 
        NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
        if (aMobile.length>0) {
            NSString *mobileTextString = [[mobileText.text componentsSeparatedByCharactersInSet:
                                           [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
                                          componentsJoinedByString:@""];
            NSString *firstNumber = [aMobile substringToIndex:1];
           if (mobileTextString.length!=10){
    
                return NO;
            }
    
        }
            return [phoneTest evaluateWithObject:aMobile];
    }
    

提交回复
热议问题