iphonemaclover iphonemaclover - 1 month ago 7
iOS Question

Regex for Name Only in UITextfield

I create below code for Regex for name that contain Alphabets only

For Eg:
John -Correct
John123-Incorrect
John 123 - Incorrect
John Micheal -it shows incorrect as its have whitespace . How to fix it?



-(BOOL)validateNameWithString:(NSString*)nameStr
{
NSString *nameRegex = @"^[a-zA-Z]*$";

NSPredicate *testRegex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
if(![testRegex evaluateWithObject:nameStr])
return NO;
else
return YES;

}

Answer

Just add the whitespace token \s to the list of allowed tokens:

^[a-zA-Z\s]*$

check this working on Regex101

And as pointed out in the comments, you need to escape the backslash

NSString *nameRegex =@"^[a-zA-Z\\s]*$";