Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing only alphabets in textField

I want to make a UITextField to accept only characters and display error when numbers or special characters are entered.But when Im doing so ,when I enter alphabets also error is displayed.Could not understand where I going wrong?

NSString *FNameReg=@"[A-Za-z]";
NSPredicate *FNametest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",FNameReg];
 if(![FNametest evaluateWithObject:txtfirstname.text])
    {
        lblvalidateFName.hidden=NO;
        [testScroll setContentOffset:CGPointMake( 0 , 74)];
        return;
    }

BUt now when I give alphabets also then also error is displayed.Y is it so ?

like image 476
Honey Avatar asked Dec 01 '25 11:12

Honey


1 Answers

Create one method for validation like this:

-(BOOL) validateAlphabets: (NSString *)alpha
{
NSString *abnRegex = @"[A-Za-z]+"; // check for one or more occurrence of string you can also use * instead + for ignoring null value 
NSPredicate *abnTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", abnRegex];
BOOL isValid = [abnTest evaluateWithObject:alpha];
return isValid;
}

Now check for the validation where you want like this:

bool checkAlphabets = [self validateAlphabets:txtfirstname.text];

if(!checkAlphabets)
{
   NSLog(@"Not Matches..");
}
else
{
  NSLog(@"Matches..");
}
like image 173
Shah Paneri Avatar answered Dec 03 '25 03:12

Shah Paneri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!