我想在textfield中输入字母数字值。如果用户只输入字符或数字,则发送按摩。即使没有特殊字符可以接受。
NSString *str = askIdTxt.text;
NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *numberSet = [NSCharacterSet decimalDigitCharacterSet];
BOOL isAlphaNumericOnly = [[str stringByTrimmingCharactersInSet:alphanumericSet] isEqualToString:@""] && ! [[str stringByTrimmingCharactersInSet:numberSet] isEqualToString:@""];
if (isAlphaNumericOnly) {
NSLog(@"isAplhaNumericOnly: %@",(isAlphaNumericOnly? @"Yes":@"No"));
}
这总是回归真实。我没有弄错。
答案 0 :(得分:6)
如何使用正则表达式:
-(BOOL)isAlphaNumericOnly:(NSString *)input
{
NSString *alphaNum = @"[a-zA-Z0-9]+";
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", alphaNum];
return [regexTest evaluateWithObject:input];
}
然后使用它
if([self isAlphaNumeric:str])
{
NSLog(@"IT IS ALPHA NUMERIC STRING");
}
修改强> 相同的技术可用于验证密码,您只需要更好的正则表达式:
-(BOOL)isPasswordStrong:(NSString *)password {
/*
8-20 chars
at least one letter
at least one number OR special character
no more than 3 repeated characters
*/
NSString *strongPass= @"^(?!.*(.)\\1{3})((?=.*[\\d])(?=.*[A-Za-z])|(?=.*[^\\w\\d\\s])(?=.*[A-Za-z])).{8,20}$";;
NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", strongPass];
return [regexTest evaluateWithObject:password];
}
使用正则表达式可以创建不同的规则,但这可以为您提供一个先机,
答案 1 :(得分:2)
Call this Method and modify it accordingly .....
-(BOOL) isPasswordValid:(NSString *)pwd
{
if ( [pwd length]<4 || [pwd length]>20 ) return NO; // too long or too short
NSRange rang;
rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if ( !rang.length ) return NO; // no letter
rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
if ( !rang.length ) return NO; // no number;
return YES;
}
答案 2 :(得分:2)
我想问题出在alphanumericCharacterSet
,这里是a part from doc:
非正式地,此集合是用作基本单位的所有字符的集合 字母,音节,表意文字和数字。
所以,我希望它会允许你不想要的角色。
您也可以尝试使用Regex:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z\\d]+$" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger matches = [regex numberOfMatchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, [str length])];
BOOL hasMatches = (matches > 0) && !error;
答案 3 :(得分:1)
试试这个
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *charactersToBlock = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
return ([string rangeOfCharacterFromSet:charactersToBlock].location == NSNotFound);
}
答案 4 :(得分:0)
试试这个:
NSCharacterSet *blockedCharacters = [[[NSCharacterSet alphanumericCharacterSet] invertedSet] retain];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}