我正在创建一个我要在名称字段中检查的表单,如果有人输入数字然后显示警告。
以下是代码:
NSString *str = abc.text;
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
if (!(valid))
{
NSLog(@"number present");
}
else
{
NSLog(@"number not present");
}
谢谢
答案 0 :(得分:1)
您可以在用户按下某个键时直接处理键盘事件
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *alphaSet = [NSCharacterSet decimalDigitCharacterSet];
BOOL isNumber= [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
if(!([textfield.text isEqualToString:@""] || textfield.text== nil )) //empty check
{
if (isNumber) {
// alert here
NSLog(@"Number not alowed");
return NO;
}
}
}
答案 1 :(得分:1)
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
if (textField == self.txt_Name) {
if(txt_Name.text.length>0)
{
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
s = [s invertedSet];
NSString *str1 = txt_Name.text;
NSRange r = [str1 rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(@"the string contains illegal characters");
txt_nameOFInfo.hidden =false;
[img_name setImage:[UIImage imageNamed:@"redot.png"]];
}
else
{
txt_nameOFInfo.hidden =true;
[img_name setImage:[UIImage imageNamed:@"gray-dot.png"]];
}
// NSLog(@"value %@",txt_lastName.text);
}
}
}
使用此代码并将委托添加到您的UItextfield我希望它适合您
答案 2 :(得分:0)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// you should check if the textfield == your Name Field
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\d{0,9}$" options:0 error:nil];
NSTextCheckingResult *numMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (numMatch) {
// alert here
NSLog(@"number present");
return NO;
} else {
NSLog(@"number not present");
}
return YES;
}