How to validate a phone number (NSString *) by NSPredicate?
Rules:
minimum 10 digits
maximum 10 digits
the first digit must be 7,8 or 9 Thanks
How to validate a phone number (NSString *) by NSPredicate?
Rules:
minimum 10 digits
maximum 10 digits
the first digit must be 7,8 or 9 Thanks
An NSPredicate
based on a regular expression will fit your requirements.
NSString *stringToBeTested = @"8123456789";
NSString *mobileNumberPattern = @"[789][0-9]{9}";
NSPredicate *mobileNumberPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mobileNumberPattern];
BOOL matched = [mobileNumberPred evaluateWithObject:stringToBeTested];
You don't need to keep the pattern in a string by itself, but regexes are complicated enough already so it makes the overall code clearer if you keep it out of the NSPredicate
format string.
You can just use below code
- (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;
}
NSString *phoneNumber = @"1234567890";
NSString *phoneRegex = @"[789][0-9]{3}([0-9]{6})?";
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
BOOL matches = [test evaluateWithObject:phoneNumber];
Below code will work for your requirement:
Function:
-(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];
}
Call it:
if ([self validatePhone:@"9833112299"])
{
NSLog(@"Valid Phone Number");
}
else
{
NSLog(@"Invalid Phone Number");
}
In any one of your view controller class at the end after last } paste below code
extension String
{
func validateMobile() -> Bool
{
return NSPredicate(format: "SELF MATCHES %@","[789][0-9].{9}").evaluate(with: self)
}
}
when you want to validate yourTxtField in any ViewController class simply call as below:
if (yourTxtField.text?.validateMobile())!
{
print("It is 10 digit, starting with 7/8/9")
}
else
{
print("Invalid mobile number")
}