Skip to content
(Python) Project: Creating Functions to Register App Users
  • AI Chat
  • Code
  • Report
  • Creating Functions to Register App Users

    Define functions to catch errors when new users register for an app!

    You are a junior developer working on a registration system for a mobile app at a small startup. The product managers have asked you to improve the current sign-up flow by integrating reusable Python functions that validate user input entered into the form.

    The previous junior developer wrote some helper functions that validate the name, email, and password. Use these functions to register users, store their data, and implement some error handling! These have been imported into the workspace for you. They will be a great help to you when registering the user, but first you have to understand what the function does! Inspect the docstrings of each of the helper functions: validate_name, validate_email and validate_password.

    1. Create a user validation function

    You will create a function validating user input using some helper functions. It will also raise errors, with meaningful feedback messages to inform users which input has failed the checks.

    Define the function

    • Use the def keyword to define a function called validate_user()
    • The function should accept three parameters: name, email and password

    Build the functions logic

    • In the function body, use an if statement and call your first helper function validate_name(name)
    • Check if the output is False by using an equality comparison operator ==
    • If the function returns a False value, then raise a ValueError in the body of your if statement and pass it a descriptive error message
    • Repeat this for the helper functions: validate_email(email) and validate_password(password)
    • If none of the three functions return a False value, then return a True value
    # Re-run this cell and examine the docstring of each function
    from python_functions import validate_name, validate_email, validate_password, top_level_domains
    
    print("validate_name\n")
    print(validate_name.__doc__)
    print("--------------------\n")
    
    print("validate_email\n")
    print(validate_email.__doc__) 
    print("--------------------\n")
    
    print("validate_password\n")
    print(validate_password.__doc__)
    
    # The top level domains variable is used in validate_email to approve only certain email domains
    print(top_level_domains)
    # 1. Function to validate user input from sign-up form
    def validate_user(name, email, password):
        """Validate the user name, email and password.
    
        Args:
            name (string): Name that we're attempting to validate.
            email (string): Email address that we're attempting to validate.
            password (string): Password that we're attempting to validate.
    
        Returns:
            Boolean: Will return True if all validation checks pass
    
        Raises ValueError if validation fails.
        """
    
        # Check if name is not valid, if not raise value error.
        if validate_name(name) == False:
            raise ValueError("Please make sure your name is greater than 2 characters!")
    
        # Check if email is not valid, if not raise value error.
        if validate_email(email) == False:
            raise ValueError("Your email address is in the incorrect format, please enter a valid email.")
    
        # Check if password is not valid, if not raise value error.
        if validate_password(password) == False:
            raise ValueError("Your password is too weak, ensure that your password is greater than 8 characters, contains a capital letter and a number.")
    
        # If none of the if not statements are triggered, return True
        return True
    validate_user
    # test 1
    validate_user("First Last Name", "[email protected]", "password1234")
    Run cancelled
    # test 2
    validate_user("Te", "[email protected]", "Password1234")
    Run cancelled
    # test 3
    validate_user("First Last Name", "[email protected]", "Password1234")
    Run cancelled
    # test 4
    validate_user("First Last Name", "[email protected]", "Password1234")

    Now that you've validated that all the user details are correct, you want to allow users to register to the app. Create a register_user() function that registers the user if all checks pass:

    • The function should take in the parameters: name, email and password
    • The function should call validate_user() to ensure that the user input is valid
    • If all checks pass, the function should create a dictionary with the keys: name, email, password
    • The function should return the new user dictionary, or the boolean value of False

    2. Create a user registration function

    You will create a function that validates the user input. If the validation passes, it will then create a new user dictionary.

    Define the function

    • Use def to define a function called register_user()
    • The function should accept parameters: name, email, password

    Input validation and user creation

    • Inside the function, utilize an if statement to check if the user input is valid by calling the validate_user() function.
    • Pass the name, email, and password parameters to the validate_user() function

    Registering valid user

    • In the body of the if statement, define a dictionary with user details called user, containing the following keys: name, email, password
    • Assign the correct values inside the dictionary; the values should be the arguments passed into the function: name, email, password
    • If the validation is successful, return the newly created user dictionary from the function.

    Handling invalid input:

    • If the validation fails, meaning the validate_user() function returns False, exit the if statement and return False from the register_user() function
    # 2. Function to register validated user if all checks have passed
    def register_user(name, email, password):
        """Attempt to register the user if they pass validation.
    
        Args:
            name (string): Name of the user
            email (string): Email address of the user
            password (string): Password of the user
    
        Returns:
            Dict: Return a dictionary with the user details
    
        Raises ValueError on missing arguments.
        """
    
        # Check if user input is valid by calling the validate user function
        if validate_user(name, email, password):
            # Create user object with details
            user = {
                "name": name,
                "email": email,
                "password": password
            }
    
            # Return user object
            return user
    
        # If validation fails, return False
        return False
    # test 1
    register_user("Last First", "[email protected]", "_assword8765")