validate the phone number and email in same text filed in objective c

穿精又带淫゛_ 提交于 2019-12-23 03:03:09

问题


Any one help to solve this issues I am new for the development

I need to login with phone number as well as email id with same textfield how could I achieve that hereby I have to set the 10 digit limit for phone number as well as US like (838)-(838)-3333 format phone number ..and email id with same text filed ..how do I validate that user enter phone number or email..any one help me to solve the issues thanks in advance here is my code

 if (!([self.usernameTextField.text validEmail] || [self.usernameTextField.text validateMobile])){
        [self ShowAlert:@"Please enter a valid email address/phonenumber"];

    }

- (BOOL)validEmail {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:self];
    return isValid;
}

- (BOOL)validateMobile {
    NSString *ACCEPTABLE_CHARECTERS = @" 0123456789+-";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
    NSString *filtered = [[self componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
   // NSString* formattedNumber = [Contact formatPhoneNumber:phoneNumber codeLength:3 segmentLength:4];
    return [self isEqualToString:filtered];
}

回答1:


here I add my answer and customize yourself based on your Need.

step-1

connect the textfield and invoke the delegate on your current class, for e.g

 @interface ViewController ()<UITextFieldDelegate>


@property (strong, nonatomic) IBOutlet UITextField *currentTextfield;

@end

step-2

get the first char on textfield delegate shouldChangeCharactersInRange and check whether it is number (phone number) or string (email)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)textEntered

{
 NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: textEntered];

NSString *abnRegex = @"[A-Za-z]+";
NSPredicate *abnTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", abnRegex];
if (([abnTest evaluateWithObject:resultingString] || resultingString.length == 0)) {
    NSLog(@"its email");
}
else
{
    NSLog(@"its phone number");
}
return YES;
}

step-3

if it is phone number then arrange the letters based on (838)-(838)-3333 format

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)textEntered

{
 NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: textEntered];

 NSString *abnRegex = @"[A-Za-z]+";
 NSPredicate *abnTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", abnRegex];
if (([abnTest evaluateWithObject:resultingString] || resultingString.length == 0)) {
    NSLog(@"its email");
}
else
{
    NSLog(@"its phone number");
 //(838)-(838)-3333
    if (range.length == 1) {
        // Delete button was hit.. so tell the method to delete the last char.
        textField.text = [self formatPhoneNumber:resultingString deleteLastChar:YES];
    } else {
        textField.text = [self formatPhoneNumber:resultingString deleteLastChar:NO ];
    }
    return false;

}
return YES;
}

-(NSString*) formatPhoneNumber:(NSString*) simpleNumber deleteLastChar:(BOOL)deleteLastChar {
if(simpleNumber.length==0) return @"";
// use regex to remove non-digits(including spaces) so we are left with just the numbers
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\s-\\(\\)]" options:NSRegularExpressionCaseInsensitive error:&error];
simpleNumber = [regex stringByReplacingMatchesInString:simpleNumber options:0 range:NSMakeRange(0, [simpleNumber length]) withTemplate:@""];

// check if the number is to long
if(simpleNumber.length>10) {
    // remove last extra chars.
    simpleNumber = [simpleNumber substringToIndex:10];
}

if(deleteLastChar) {
    // should we delete the last digit?
    simpleNumber = [simpleNumber substringToIndex:[simpleNumber length] - 1];
}

// 123 456 7890
// format the number.. if it's less then 7 digits.. then use this regex.
if(simpleNumber.length<7)
    simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d+)"
                                                           withString:@"($1)-($2)"
                                                              options:NSRegularExpressionSearch
                                                                range:NSMakeRange(0, [simpleNumber length])];

else   // else do this one..
    simpleNumber = [simpleNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d+)"
                                                           withString:@"($1)-($2)-$3"
                                                              options:NSRegularExpressionSearch
                                                                range:NSMakeRange(0, [simpleNumber length])];
return simpleNumber;
}

step-4

finally validate your email or phone number on button action if it is the valid or not.

NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];

NSString *phoneRegex = @" (((\d{3}) ?)-((\d{3}) ?))?-\d{4}";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];

if([emailTest evaluateWithObject:currentTextfield.text] == NO && [phoneTest evaluateWithObject:currentTextfield.text] == NO)
{
    NSLog(@"Please enter a valid email address/phonenumber");

}

else
{
    //login successful

}



回答2:


Use this method it will be helpfull more and save your valuable time.

 -(BOOL)textField:(UITextField *)textField 
  shouldChangeCharactersInRange:(NSRange)range replacementString: 
  (NSString *)string{

if (textField == _userIdTF){
     NSString *totalString = [NSString stringWithFormat:@"%@%@",_userIdTF.text,string];
    NSString *prefix;

    if ([totalString length] == 1){
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"checkValue"];
    }

    if ([totalString length] >= 1){

        prefix = [totalString substringToIndex:1];
            NSLog(@"first letter %@",prefix);

            if ([prefix isEqualToString:@"1"] || [prefix isEqualToString:@"2"] || [prefix isEqualToString:@"2"] || [prefix isEqualToString:@"0"] || [prefix isEqualToString:@"3"]|| [prefix isEqualToString:@"4"] || [prefix isEqualToString:@"5"] || [prefix isEqualToString:@"6"] || [prefix isEqualToString:@"7"] || [prefix isEqualToString:@"8"] || [prefix isEqualToString:@"9"]){

                [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"checkValue"];
                NSLog(@"checkvalu %@",[[NSUserDefaults standardUserDefaults]objectForKey:@"checkValue"]);

        }else{

        }
            }
    NSString *checkValue = [[NSUserDefaults standardUserDefaults]objectForKey:@"checkValue"];
    NSLog(@"checkvalu %@",checkValue);
    if (  [checkValue  isEqual: @"1"] ) {
        if ([totalString containsString:@"05"]) {

            [totalString stringByReplacingOccurrencesOfString:totalString withString:@"+966"];
            NSLog(@"phone number");

            _userIdTF.text = [totalString stringByReplacingOccurrencesOfString:totalString withString:@"+966"];
        }
    }else{
          prefix = totalString;
    }

    NSUInteger newLength = [textField.text length] + [string 
 length] - range.length;

 if ([self.userIdTF.text containsString:@"+"]){

    NSLog(@"number ppad");

    NSString *acceptedCharsters = @"0123456789";


    NSCharacterSet *cs = [[NSCharacterSet 
 characterSetWithCharactersInString:acceptedCharsters] 
 invertedSet];

    NSString *filtered = [[string 
 componentsSeparatedByCharactersInSet:cs] 
 componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
 }else{

 }

 return (newLength > 50) ? NO : YES;
 }
  else{
  return YES;
  }
 }


来源:https://stackoverflow.com/questions/46538998/validate-the-phone-number-and-email-in-same-text-filed-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!