2020年3月20日 星期五

Check String is Email or Url


Mail check :



-(BOOL) NSStringIsValidEmail:(NSString *)checkString

{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *email = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [email evaluateWithObject:checkString];
}



Url check :

-(BOOL)isUrlString:(NSString *)checkStr

{
    NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];

    /*
     for not en-us Character
     */

    NSString *urlStr = [checkStr stringByAddingPercentEncodingWithAllowedCharacters:set];

    NSURL *url = [NSURL URLWithString:urlStr]; //avoid get null

    if ((url && url.scheme && url.host) || (([[urlStr uppercaseString] hasPrefix:@"HTTP"] || [[urlStr uppercaseString] hasPrefix:@"HTTPS"]) && ![self NSStringIsValidEmail:urlStr]))

    {
        //string is url ...
        return YES;
    }
    return NO;
}

沒有留言:

張貼留言