web-dev-qa-db-fra.com

Comment puis-je restreindre les caractères spéciaux dans UITextField sauf les points et les traits de soulignement?

Comment puis-je limiter les caractères spéciaux dans une UITextField à l'exception des points et des traits de soulignement? 

J'ai essayé l'extrait de code ci-dessous, mais sans succès:

#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;
        }
}
28
Graham Bell

Essayez le bloc de code donné ci-dessous, cela a bien fonctionné pour moi.

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)
}

Objectif 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];
}

J'espère que cela fonctionnera pour vous aussi.

90
Mrunal

Essaye ça

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

vous pouvez faire votre propre set avec 

NSCharacterSet  *set= [NSCharacterSet characterSetWithCharactersInString:@"<all your symbols you want to ignore>"];
4
amar

Swift 2.2 basé sur réponse de Mrunal :

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;

}
3
Evdzhan Mustafa

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

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

[TestResult evaluateWithObject:@"YourTestString"]; 

Dernier retour booléen true/false

En méthode

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

solution 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)
    }
2
Sourabh Sharma

Cela peut vous aider à essayer ceci .. et laissez-moi savoir s'il vous plaît

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

Swift 4

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

Méthode de délégué 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
}
1
Sunil Targe
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;
0
GOWTHAM