Check if NSString contains alphanumeric + underscore characters only

后端 未结 7 1823
余生分开走
余生分开走 2021-01-30 00:52

I\'ve got a string that needs to be only a-z, 0-9 and _

How do I check if the input is valid? I\'ve tried this but it accepts letter like å,ä,ö,ø etc.

NS         


        
7条回答
  •  耶瑟儿~
    2021-01-30 01:19

    You can use a predicate:

    NSString *myRegex = @"[A-Z0-9a-z_]*"; 
    NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myRegex]; 
    NSString *string = nameField.text;
    BOOL valid = [myTest evaluateWithObject:string];
    

    Edit: I don't noticed that you are using [NSString stringWithString:nameField.text].

    Use nameField.text instead.

提交回复
热议问题