Check UITextfield have only Alphabet not numeric value

402 Views Asked by At

I am creating one form I want to check in Name Field if any one enter Number then show alert.

Here is the code:

NSString *str = abc.text; 
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet]; 
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""]; 
if (!(valid)) 
{ 
    NSLog(@"number present"); 
} 
else 
{   
    NSLog(@"number not present"); 
}

Thanks

3

There are 3 best solutions below

0
On BEST ANSWER
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
if (textField == self.txt_Name) {

    if(txt_Name.text.length>0)
    {
        NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];
        s = [s invertedSet];
        NSString *str1 = txt_Name.text;
        NSRange r = [str1 rangeOfCharacterFromSet:s];
        if (r.location != NSNotFound) {
            NSLog(@"the string contains illegal characters");
            txt_nameOFInfo.hidden =false;
            [img_name setImage:[UIImage imageNamed:@"redot.png"]];

        }
        else
        {
            txt_nameOFInfo.hidden =true;
            [img_name setImage:[UIImage imageNamed:@"gray-dot.png"]];

        }
      //  NSLog(@"value %@",txt_lastName.text);
    }

}

}

Used this code and add delegate to your UItextfield I hope it work for you

1
On
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // you should check if the textfield == your Name Field
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\d{0,9}$" options:0 error:nil];
    NSTextCheckingResult *numMatch = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];

    if (numMatch) {
        // alert here
        NSLog(@"number present");
        return NO;
    } else {
        NSLog(@"number not present");
    }

    return YES;
}
0
On

You can directly handle keyboard events every-time a user presses a key

     -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
        {  
        NSCharacterSet *alphaSet = [NSCharacterSet decimalDigitCharacterSet];
            BOOL isNumber= [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
if(!([textfield.text isEqualToString:@""] || textfield.text== nil )) //empty check
{
           if (isNumber) {
                // alert here
                NSLog(@"Number not alowed");
                return NO;
            } 
}

        }