我有两个文本字段,一个是Zip,另一个是电话号码。我想验证zip文本字段只包含6位数字的号码和电话号码文本字段只包含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;
}
您的Zip和电话号码都是整数文本字段,那么为什么不将文本字段的keyboardtype
更改为numberpad
呢?然后,在你的shouldChangeCharactersInRange
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * currentStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
if (textfield.tag == 10 && currentStr.length == 6) // Zip Textfield
{
return false;
}
if (textfield.tag == 11 && currentStr.length == 10) // Phone Textfield
{
return false;
}
}
试试这个:
- (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;