Неразрешенный список специальных символов - PullRequest
0 голосов
/ 15 марта 2019

Итак, я пишу проект, который проверяет наличие ошибок в символах электронной почты. Я искал здесь без чего-то, что было полезно, а также на duckduckgo. Он работает нормально, но я вижу следующее на оболочке:

e mail: abc @ xyz.com   *** ERROR: 2. The number of @'s in your email is suspect. ***
e mail: .abc@xyz.com    *** ERROR: 2. The number of @'s in your email is suspect. ***
e mail: abc@xyz.c   *** ERROR: 2. The number of @'s in your email is suspect. ***

Заметьте, что функция testAtsign (2. The number of @'s in your email is suspect.) занимает некоторое место, где должны отображаться другие ошибки, такие как не разрешенные специальные символы?

Я думаю, что есть проблема с моей функцией testSpecialChars, которая позволяет функции testAtsign вступать во владение. Может ли быть проблема с недопустимым списком?

Любые идеи очень ценятся.

emailList = ["abc@xyz.com",
             "abc@@xyz.com",
             "@xyz.com",
             "abc.xyz.com",
             "abc@x.yz",
             "abc@xyz.c",
             "a@b.c",
             "abc@xyz..com",
             "abc.@xyz.com",
             "abc@.xyz.com",
             "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@aaaaaa.aaaaa",
             "' or 1=1 '==",
             "abc@xyz.$%",
             "abc@xyz.()",
             "abc'@xyz.com",
             "aaaaa@aaaaa",
             "abc @ xyz.com",
             ".abc@xyz.com",
             "abc@xyz.c"]



def errorMessage(email, error):
    print("e mail: {} \t*** ERROR: {} ***".format(email, error))

def testAtsign (email):
    if "@" in email:
        #should be 1 @
        #are there more?
        atCount = 0
        for character in email:
            if character == "@":
                atCount += 1

            if atCount != 1:
                errorMessage(email, "2. The number of @'s in your email is suspect.")
                return True
            elif email[0] == "0":
                errorMessage(email, "3.The @ is not in a valid position.")
                return True
            else:
                testLast5 = email[-5]
                if "@" in testLast5:
                    errorMEssage(email, "4. Okay, your @ is not in the last 5 characters, whats up with you?")
                    return True
                else:
                    return False
    else:
        errorMessage(email, "5. your @ is missing")
        return True


def testDot(email):
    if "." in email:
        #has to be at least ONE

        if email[0] == ".":
            errorMessage(email, "10. Your '.' is in the first position.")
            return True
        testLast2 = email[-2:]
        if "." in testLast2:
            errorMessage(email, "11. Your '.' is in the last position.")
            return True
        #should not be doubled or next to @
        elif ".." in email or ".@" in email or "..@" in email or "@." in email or "@.." in email:
            errorMessage(email, "6. Were sensing an erorr in your '.' config.")
            return True

    else:
        errorMessage(email, "7. Where is the '.'?")
        return True

def testSpecialChars(email) :
    #first test for spaces
    if " " in email:
        errorMessage(email, "8. We dont allow spaces in our emails here.")
        return True

    #create list of unallowables
    unallowable = "! # $ % ^ & * ( ) : ; < > ? / { } =".split()
    #add quotes
    unallowable.append('"')
    unallowable.append("'")

    for character in email:
        if character in unallowable:
            errorMEssage(email, "9. Character {} is not allowed".format(character))
            return True









for email in emailList:
    foundError = False
    if len(email) < 7 or len(email) > 30:
        errorMessage(email, "1. Invalid Length")  #labeling the errors with numbers to keep track
        foundError = True

    if not foundError:
        foundError = testAtsign(email)

    if not foundError:
        foundError = testDot(email)
    if not foundError:
        foundError = testSpecialChars(email)

    if not foundError:
        print("Rad, your email seems valid.".format(email))

    print("flag")

Ответы [ 2 ]

0 голосов
/ 16 марта 2019

В этой функции код testAtsign проходит по адресу электронной почты для подсчета символов "@" и выполняет проверку счетчика внутри цикла .Следовательно, если первый символ в адресе не равен «@», функция всегда будет возвращать True, поскольку счетчик «@» не равен единице.

Исправьте это, переместив проверки за пределы цикла;фактически цикл можно полностью удалить с помощью метода count строк Python для получения количества символов "@" в каждом адресе.

Фиксированная функция будет выглядеть следующим образом:

def testAtsign(email):
    if "@" in email:
        # should be 1 @
        # are there more?
        atCount = email.count("@")

        if atCount != 1:
            errorMessage(email, "2. The number of @'s in your email is suspect.")
            return True
        elif email[0] == "0":  # <- this might need fixing?
            errorMessage(email, "3.The @ is not in a valid position.")
            return True
        else:
            testLast5 = email[-5]  # <- this only gets a single character
            if "@" in testLast5:
                errorMessage(
                    email,
                    "4. Okay, your @ is not in the last 5 characters, whats up with you?",
                )
                return True
            else:
                return False
    else:
        errorMessage(email, "5. your @ is missing")
0 голосов
/ 15 марта 2019

Сначала вы проверяете testAtsign (). Внутри функции, если обнаружена какая-либо ошибка, вы меняете значение foundError на «True». Поскольку значение foundError обновляется до True, все остальные условия if (для testDot () и testSpecialChars ()) не выполняются и не выполняются вообще. То же самое с оператором if if len(email) < 7 or len(email) > 30. В тот момент, когда это верно, и foundError обновляется до True внутри него, даже testAtSign () не будет выполняться.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...