我有一个文本字段,用户可以在其中输入IP地址或任何网址。但问题是我只需要在用户输入IP地址时进行验证,如果他输入了URL,则不应该验证。
我完成的是:
-(BOOL)ipValidationUsingRegex:(NSString *)ipAddressStr
{
NSString *ipValidStr = ipAddressStr;
NSString *ipRegEx =
@"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", ipRegEx];
BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:ipValidStr];
NSLog(@"myStringMatchesRegEx = %d ",myStringMatchesRegEx);
return myStringMatchesRegEx;
}
-(IBAction)saveAction:(id)sender
{
if([msaTextField.text length] == 0 || [msrpTextField.text length] == 0)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"Please enter all fields" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
if(([msaTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789."]].length > 0) ) {
//URL
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:msaTextField.text forKey:@"MSA"];
// saving an NSString
[prefs setObject:msrpTextField.text forKey:@"MSRP"];
[prefs synchronize];
//[self.navigationController popViewControllerAnimated:YES];
[self dismissModalViewControllerAnimated:YES];
}
else {
//IP
if(([self ipValidationUsingRegex:msaTextField.text] == YES) )
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:msaTextField.text forKey:@"MSA"];
// saving an NSString
[prefs setObject:msrpTextField.text forKey:@"MSRP"];
[prefs synchronize];
//[self.navigationController popViewControllerAnimated:YES];
[self dismissModalViewControllerAnimated:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"IP range is Invalid" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
}
}
我在这里遇到的问题是IP地址正确验证,但事情就是当我输入网址时,它也说Ip的无效范围作为警报。
我输入的网址类似于http://www.yahoo.com
请给我建议