swift中单个UITextField的多个验证

时间:2016-09-01 05:37:40

标签: ios swift uitextfield

我希望在 Swift

中对VIN编号UITextField进行多次验证
  • 它应该是 Capital 字母

  • 它可以包含0-9 数字

  • 无空格特殊 字符允许

  • 总长度必须 16 字符

3 个答案:

答案 0 :(得分:4)

Swift 3.0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if string.characters.count == 0 {
        return true
    }

    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)

    return prospectiveText.containsOnlyCharactersIn(matchCharacters: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&
        prospectiveText.characters.count <= 16
}

extension String {

    func containsOnlyCharactersIn(matchCharacters: String) -> Bool {

        let disallowedCharacterSet = NSCharacterSet(charactersIn: matchCharacters).inverted
        return self.rangeOfCharacter(from: disallowedCharacterSet) == nil
    }
}

答案 1 :(得分:1)

The best solution is regular expression! Simple as that [A-Z0-9]{16}.

NSString *testString=@"ABSDF9DFDSFPOIS1";
NSString *regExPattern = @"[A-Z0-9]{16}";

NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger regExMatches = [regEx numberOfMatchesInString:testString options:0 range:NSMakeRange(0, [testString length])];

if (regExMatches==0) {
//Not matched
}

Take a look here to see how this regex works and you will realise how flexible is to change.

答案 2 :(得分:0)

您可以为Objective-C实现以下所有验证

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField==YOUR_USER_NAME_TEXTFIELD || textField == YOUR_PASSWORD_TEXTFIELD)
    {

        NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
        for (int i = 0; i < [string length]; i++)
        {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c])
            {
                return NO;
            }
        }

        return YES;
    }

    return YES;
}

总长度必须为16个字符

您可以计算yourtextfield的长度。