如何通过NSPredicate验证电话号码(NSString *)?
规则:
最少10位
最多10位
第一个数字必须是7,8或9 感谢
答案 0 :(得分:6)
基于正则表达式的NSPredicate
符合您的要求。
NSString *stringToBeTested = @"8123456789";
NSString *mobileNumberPattern = @"[789][0-9]{9}";
NSPredicate *mobileNumberPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileNumberPattern];
BOOL matched = [mobileNumberPred evaluateWithObject:stringToBeTested];
您不需要将模式本身保留在字符串中,但正则表达式已足够复杂,因此如果将其保留在NSPredicate
格式字符串之外,则会使整个代码更清晰。
答案 1 :(得分:2)
您可以使用以下代码
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
{
if(textField.tag == 111)
{
if([self MobileNumberValidate:string] == TRUE)
return YES;
else
return NO;
}
return YES;
}
#pragma mark - Mobile Number validation
- (BOOL)MobileNumberValidate:(NSString*)number
{
NSString *numberRegEx = @"[0-9]";
NSPredicate *numberTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegEx];
if ([numberTest evaluateWithObject:number] == YES)
return TRUE;
else
return FALSE;
}
答案 2 :(得分:0)
NSString *phoneNumber = @"1234567890";
NSString *phoneRegex = @"[789][0-9]{3}([0-9]{6})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
答案 3 :(得分:0)
以下代码适用于您的要求:
功能:
-(BOOL)validatePhone:(NSString *)enteredPhoneNumber
{
NSString *phoneRegex = @"[789][0-9]{9}";
// OR below for advanced type
//NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
return [phoneTest evaluateWithObject:enteredPhoneNumber];
}
称之为:
if ([self validatePhone:@"9833112299"])
{
NSLog(@"Valid Phone Number");
}
else
{
NSLog(@"Invalid Phone Number");
}
答案 4 :(得分:0)
在您的任意一个视图控制器类中,在末尾} 粘贴以下代码
extension String
{
func validateMobile() -> Bool
{
return NSPredicate(format: "SELF MATCHES %@","[789][0-9].{9}").evaluate(with: self)
}
}
当您想在任何ViewController类中验证yourTxtField时,只需按以下方式调用:
if (yourTxtField.text?.validateMobile())!
{
print("It is 10 digit, starting with 7/8/9")
}
else
{
print("Invalid mobile number")
}