iphonemaclover iphonemaclover - 1 year ago 86
iOS Question

Regex for Name Only in UITextfield

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

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

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

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


Answer Source

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


check this working on Regex101

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

NSString *nameRegex =@"^[a-zA-Z\\s]*$";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download