IT

iOS 2.0에서 이메일 주소를 확인하는 모범 사례는 무엇입니까

lottoking 2020. 5. 27. 07:54
반응형

iOS 2.0에서 이메일 주소를 확인하는 모범 사례는 무엇입니까


iOS 2.0에서 사용자가 입력 한 이메일 주소를 확인하는 가장 확실한 방법은 무엇입니까?

참고 : 이것은 iOS 2.0에만 해당되는 역사적 질문이며 그 연령 및 그와 관련된 다른 질문 수는 은퇴 할 수 없으며 "현대적인"질문으로 변경해서는 안됩니다.


정규식사용하여 전자 메일 주소 확인에 대한 답변 은 RFC 5322에 지정된 문법이 기본 정규식에 비해 너무 복잡하다는 것을 자세하게 설명합니다.

MKEmailAddress 와 같은 실제 파서 접근 방식을 권장합니다 .

빠른 정규식 솔루션으로 DHValidation의 다음 수정을 참조하십시오 .

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}

RFC를 읽으십시오. 이메일 주소를 구문 분석 / 청소 / 확인하는 방법을 알고 있다고 생각하는 사람은 거의 모두 잘못되었습니다.

http://tools.ietf.org/html/rfc2822 섹션 3.4.1은 매우 유용합니다. 주의

dtext = NO-WS-CTL /; 비 공백 컨트롤

                        % d33-90 /; US-ASCII의 나머지
                        % d94-126; "["를 포함하지 않는 문자,
                                        ; "]"또는 "\"

예, +, '등이 모두 합법적임을 의미합니다.


지금까지 내가 찾은 가장 좋은 해결책은 NSString 카테고리를 통해 정규 표현식에 액세스 할 수있는 프로젝트 RegexKitLite추가하는 것입니다 .

프로젝트에 추가하는 것은 매우 고통스럽지 않으며 일단 정규식 이메일 유효성 검사 논리가 작동합니다.


좋은 시작은 당신이 무엇을 결정하고 이메일 주소로 수락하고 싶지 않습니까?

이메일 주소의 99 %는 다음과 같습니다 : bob.smith@foo.com 또는 fred@bla.edu

그러나 다음과 같은 이메일 주소를 갖는 것은 기술적으로 합법적입니다. f !#$%&'*+-/=?^_{|} ~ "ha!"@ com

세계에는 최상위 도메인에 대해 소수의 유효한 전자 메일 만있을 수 있으며 거의 ​​모든 다른 문자 (특히 따옴표 및 백틱)를 사용하는 사람이 거의 없기 때문에 모두 유효하지 않은 것으로 가정 할 수 있습니다. 그러나 당신은 의식적인 결정으로 그렇게해야합니다.

그 외에도 Paul이 말한 것을 수행하고 입력을 다음과 같은 정규식과 일치 시키십시오. ^ [A-Z0-9 ._ % +-] + @ [A-Z0-9 .-] +. [AZ] { 2,} $

그것은 거의 모든 사람의 이메일 주소와 일치 할 것입니다.


정규 표현식에 중점을 두는 것이 좋지만 이것은 첫 번째 단계이며 필요한 단계입니다. 좋은 유효성 검사 전략을 위해 고려해야 할 다른 단계도 있습니다.

내 머리 위에 두 가지가 있습니다.

  1. 도메인이 실제로 존재하는지 확인하는 DNS 유효성 검사

  2. dns 유효성 검사 후 smtp 유효성 검사를 수행하도록 선택할 수도 있습니다. smtp 서버로 전화를 보내 사용자가 실제로 있는지 확인하십시오.

이러한 방식으로 모든 종류의 사용자 오류를 파악하고 유효한 전자 메일인지 확인할 수 있습니다.


이 기능은 간단하지만 이메일 주소를보다 철저하게 확인합니다. 예를 들어, RFC2822에 따르면 이메일 주소에는 firstname..lastname @ domain..com과 같이 두 개의 마침표가 한 행에 포함되어서는 안됩니다.

이 함수에서 볼 수 있듯이 정규식에 앵커를 사용하는 것도 중요합니다. 앵커가 없으면 다음 이메일 주소가 유효한 것으로 간주됩니다. first; name) last @@ domain.com (blahlastname@domain.com 섹션이 유효 하기 때문에 처음에는 name; name)무시 하고 끝에는 blah 를 강제합니다. 전체 표현식을 검증하는 정규식 엔진.

이 함수는 iOS 2에는 존재하지 않는 NSPredicate를 사용합니다. 불행히도 asker를 도울 수는 없지만 새로운 버전의 iOS를 가진 사람들을 도울 것입니다. 이 함수의 정규 표현식은 여전히 ​​iOS 2의 RegExKitLite에 적용될 수 있습니다. 그리고 iOS 4 이상을 사용하는 사람들을 위해 이러한 정규 표현식은 NSRegularExpression으로 구현 될 수 있습니다.

- (BOOL)isValidEmail:(NSString *)email
{
    NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
    NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
    NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
}

See validate email address using regular expression in Objective-C.


NSString *emailString = textField.text; **// storing the entered email in a string.** 
**// Regular expression to checl the email format.** 
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailReg]; 
if (([emailTest evaluateWithObject:emailString] != YES) || [emailStringisEqualToString:@""]) 
{ 
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:@" Enter Email in" message:@"abc@example.com format" delegate:self 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

enter code here

[loginalert show]; 
[loginalert release]; 
} 
If email is invalid, it will remind the user with an alert box. 
Hope this might be helpful for you all. 

I have found that using a regular expression works quite well to validate an email address.

The major downside to regular expressions of course is maintainability, so comment like you have never commented before. I promise you, if you don't you will wish you did when you go back to the expression after a few weeks.

Here is a link to a good source, http://www.regular-expressions.info/email.html.


Digging up the dirt, but I just stumbled upon SHEmailValidator which does a perfect job and has a nice interface.


Many web sites provide RegExes but you'd do well to learn and understand them as well as verify that what you want it to do meets your needs within the official RFC for email address formats.

For learning RegEx, interpreted languages can be a great simplifier and testbed. Rubular is built on Ruby, but is a good quick way to test and verify: http://www.rubular.com/

Beyond that, buy the latest edition of the O'Reilly book Mastering Regular Expressions. You'll want to spend the time to understand the first 3 or 4 chapters. Everything after that will be building expertise on highly optimized RegEx usage.

Often a series of smaller, easier to manage RegExes are easier to maintain and debug.


Here is an extension of String that validates an email in Swift.

extension String {

    func isValidEmail() -> Bool {
        let stricterFilter = false
        let stricterFilterString = "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"
        let laxString = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
        let emailRegex = stricterFilter ? stricterFilterString : laxString
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: self)
    }
}

Copied from the answer to: Check that an email address is valid on iOS


You shouldn't try to use regex to validate an email. With ever changing TLDs, your validator is either incomplete or inaccurate. Instead, you should leverage Apple's NSDataDetector libraries which will take a string and try to see if there are any known data fields (emails, addresses, dates, etc). Apple's SDK will do the heavy lifting of keeping up to date with TLDs and you can piggyback off of their efforts!! :)

Plus, if iMessage (or any other text field) doesn't think it's an email, should you consider an email?

I put this function in a NSString category, so the string you're testing is self.

- (BOOL)isValidEmail {
    // Trim whitespace first
    NSString *trimmedText = [self stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
    if (self && self.length > 0) return NO;

    NSError *error = nil;
    NSDataDetector *dataDetector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:&error];
    if (!dataDetector) return NO;

    // This string is a valid email only if iOS detects a mailto link out of the full string
    NSArray<NSTextCheckingResult *> *allMatches = [dataDetector matchesInString:trimmedText options:kNilOptions range:NSMakeRange(0, trimmedText.length)];
    if (error) return NO;
    return (allMatches.count == 1 && [[[allMatches.firstObject URL] absoluteString] isEqual:[NSString stringWithFormat:@"mailto:%@", self]]);
}

or as a swift String extension

extension String {
    func isValidEmail() -> Bool {
        let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return false
        }
        let allMatches = dataDetector.matches(in: trimmed, options: [], range: NSMakeRange(0, trimmed.characters.count))

        return allMatches.count == 1 && allMatches.first?.url?.absoluteString == "mailto:\(trimmed)"
    }
}

// Method Call
NSString *email = @"Your Email string..";

BOOL temp = [self validateEmail:email];

if(temp)
{
// Valid
}
else
{
// Not Valid
}
// Method description

- (BOOL) validateEmail: (NSString *) email {
    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:email];
    return isValid;
}

참고 URL : https://stackoverflow.com/questions/800123/what-are-best-practices-for-validating-email-addresses-on-ios-2-0

반응형