如何限制UITextField中除点和下划线之外的特殊字符?

时间:2013-01-28 08:11:39

标签: ios objective-c uitextfield

除了点和下划线外,如何限制UITextField中的特殊字符?

我已尝试过下面的代码段,但没有运气:

#define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
         NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];
        if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1){
            NSLog(@"not allowed");
            return NO;
        }
        else{
            return YES;
        }
}

10 个答案:

答案 0 :(得分:93)

尝试下面给出的代码块,它对我来说很好。

SWIFT 3.0

let ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let cs = NSCharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
    let filtered = string.components(separatedBy: cs).joined(separator: "")

    return (string == filtered)
}

目标C

#define ACCEPTABLE_CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
      NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

      NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

      return [string isEqualToString:filtered];
}

希望它也适合你。

答案 1 :(得分:4)

试试这个

NSCharacterSet  *set= [NSCharacterSet symbolCharacterSet];
if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {
    // valid
} else {
    // invalid
}

您可以使用

创建自己的设置
NSCharacterSet  *set= [NSCharacterSet characterSetWithCharactersInString:@"<all your symbols you want to ignore>"];

答案 2 :(得分:3)

NSString *Regex = @"[A-Za-z0-9^]*";

NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];

[TestResult evaluateWithObject:@"YourTestString"];

最后返回布尔值true / false

  

在方法

+ (BOOL) validateSpecialCharactor: (NSString *) text {
NSString *Regex = @"[A-Za-z0-9^]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
return [TestResult evaluateWithObject:text];
}

答案 3 :(得分:3)

Swift 2.2基于Mrunal's answer

let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";
func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool
{
    let set = NSCharacterSet(charactersInString: notAllowedCharacters);
    let inverted = set.invertedSet;

    let filtered = string
        .componentsSeparatedByCharactersInSet(inverted)
        .joinWithSeparator("");
    return filtered == string;

}

答案 4 :(得分:2)

  

Swift 3.1解决方案

let ACCEPTABLE_CHARACTERS = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let cs = CharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
        let filtered: String = (string.components(separatedBy: cs) as NSArray).componentsJoined(by: "")
        return (string == filtered)
    }

答案 5 :(得分:1)

这可能会帮助你试试这个......请告诉我

-(BOOL)isHaveSpecialChar:(NSString*)str{
NSString *customStr = @"~`!@#$%^&*()+=-/;:\"\'{}[]<>^?, ";
NSCharacterSet *alphaSet = [NSCharacterSet characterSetWithCharactersInString:customStr];
BOOL isHaveSpecialChar = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
return !isHaveSpecialChar;
}

答案 6 :(得分:1)

快捷键4

let RISTRICTED_CHARACTERS = "'*=+[]\\|;:'\",<>/?%"

UITextField委托方法:

func textField(_ textField: UITextField, shouldChangeCharactersIn _: NSRange, replacementString string: String) -> Bool {
    let set = CharacterSet(charactersIn: RISTRICTED_CHARACTERS)
    let inverted = set.inverted
    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    return filtered != string
}

答案 7 :(得分:0)

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

    let set = NSCharacterSet(charactersIn: "0123456789")
    let inverted = set.inverted;

    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    return filtered == string;

答案 8 :(得分:0)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let cs = NSCharacterSet.decimalDigits.inverted
    let filtered = string.components(separatedBy: cs).joined(separator: "")
    return (string == filtered)
}

答案 9 :(得分:-1)

试试这个:

NSString *str = @"___asdf.SHiv._.l.asg.  g.g._ASdgASG_.......asfgads.g.   .._____fdgdsfghsdfgh";

    str= [str stringByReplacingOccurrencesOfString:@"." withString:@""];
    str=[str stringByReplacingOccurrencesOfString:@"_" withString:@""];
    str=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    str=[str stringByTrimmingCharactersInSet:[NSCharacterSet alphanumericCharacterSet]];

    if ([str isEqualToString:@""]) {
        NSLog(@"valid");
    }
    else {
        NSLog(@"invalid");
    }