iOS中UITextField的验证[重复]
Posted
技术标签:
【中文标题】iOS中UITextField的验证[重复]【英文标题】:Validation on UITextField in iOS [duplicate] 【发布时间】:2014-02-10 06:39:28 【问题描述】:我创建了一个UITextField
,并且我想对 textfield(userName) 进行验证,以便只允许使用字符。如果用户输入了数字或特殊字符等字母以外的任何其他内容,则不应出现,并且应该有显示相同内容的通知。
【问题讨论】:
【参考方案1】:#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
NSCharacterSet *blockedCharacters = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
if (!([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound))
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Only allow alphabet." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[alert show];
return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
【讨论】:
【参考方案2】:你可以试试这个:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
if(textField==YOUR_TEXTFIELD_NAME)
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
for (int i = 0; i < [string length]; i++)
unichar c = [string characterAtIndex:i];
if (![myCharSet characterIsMember:c])
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Numbers not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
return NO;
return YES;
确保为文本字段设置委托。
【讨论】:
感谢重播,但此代码也允许 1.您是否将 UITextField 与 IBOutlet 连接? 2. 您是否将 UITextFieldDelegate 设置为您的文本字段? 先生,downvoter.. 想解释一下为什么不赞成? ://【参考方案3】:try this
NSCharacterSet *blockedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
【讨论】:
【参考方案4】:#define ACCEPTABLE_NUMBER @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
NSCharacterSet *acceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_NUMBER]invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:acceptedInput] componentsJoinedByString:@""];
if ((![filtered isEqualToString:string]))
return NO;
【讨论】:
以上是关于iOS中UITextField的验证[重复]的主要内容,如果未能解决你的问题,请参考以下文章
用于在 Swift 中为 UITextField 验证 Civil ID 的正则表达式 [重复]