I am doing the following task:
Write a program for Master Your Credentials: A Tricky Validation Script for Emails and Passwords
Instructions
- Get the input their email address
- Use
validate_email()
to check the email format.- Get the input their password.
- Use
validate_password()
to check the password strength.- Continue prompting and validating until both email and password are valid.
Notes
- The email must have one ‘@’ and at least one in the domain part.
validate_email()
ensures the email format is correct.- The password must be at least 8 characters long.
validate_password()
checks for length, digits, and letters.- The program keeps asking for input until both email and password are valid.
Sample Input:
<code>[email protected]password@123</code><code>[email protected] password@123 </code>[email protected] password@123
Sample Output:
<code>Email and password are valid.Validation process completed.</code><code>Email and password are valid. Validation process completed. </code>Email and password are valid. Validation process completed.
This is my attempt:
import re
def validate_email(email):
if not email:
raise ValueError("Email cannot be empty")
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$"
if re.match(pattern, email):
return True
return False
def validate_password(password):
if not password:
raise ValueError("Password cannot be empty")
pattern = r"^(?=.*[a-zA-Z])(?=.*d).{8,}$"
if re.match(pattern, password):
return True
return False
def main():
while True:
try:
email = input("Enter your email address: ")
if not validate_email(email):
print("Invalid email format. Please ensure the email has exactly one '@' and at least one '.' in the domain part.")
continue
password = input("Enter your password: ")
if not validate_password(password):
print("Invalid password. Please ensure the password is at least 8 characters long and includes at least one digit and one letter.")
continue
print("Email and password are valid. Validation process completed.")
break
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()
There are test cases:
TestCase 1:
Purpose: Handling errors and exceptions.
Hint: Ensure your email has exactly one ‘@’ and at least one ‘.’ in the domain part.
TestCase2:
Purpose: Handling errors and exceptions.
Hint: Verify the email’s username (before ‘@’) and domain (after ‘@’) are not empty.
TestCase3:
Purpose: Handling errors and exceptions.
Hint: Ensure your password is at least 8 characters long.
TestCase4:
Purpose: Handling errors and exceptions.
Hint: Include at least one digit and one letter in your password.
TestCase5:
Purpose: Handling errors and exceptions.
Hint: Pay attention to the error messages to understand what needs to be corrected.
The test cases 2, 3 and 4 have failed. What is going wrong here?