我有两个文本区域,一个是Zip,另一个是电话号码。我想验证zip文本字段只包含6位数字和电话号码textfield只包含10位数字。我正在使用以下代码。我难以理解的是,我无法同时验证两个文本域。enter code here
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField.tag != 10 && textField.tag !=11)
if(string.length == 0)
return YES;
if (zipTxt.text.length == 6)
return NO;
if(phoneTxt.text.length == 10)
return NO;
NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound)
{
return NO;
}
return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if (textField.tag == 10)
{
if (zipTxt.text.length<6)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please enter a valid zip number" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
if (textField.tag ==11)
{
if(phoneTxt.text.length < 10)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Please enter a valid phone number" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
return YES;
}
答案 0 :(得分:2)
您的Zip和电话号码都是整数文本字段,因此您不能将 textfield 的Sum
更改为keyboardtype
。然后,在numberpad
shouldChangeCharactersInRange
答案 1 :(得分:1)
试试这个:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(range.length + range.location > textField.text.length)
{
return NO;
}
NSUInteger newLength = [textField.text length] + [string length] - range.length;
if(textField == ziptextField){
return newLength <= 6;
}
else if(textField == phonenukmbertextField){
return newLength <= 10;
}
return YES;