Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Task 2 A: Raising a request with clear errors

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

70 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The form that says "error"

You fill in a long form online. You press Send. The page says "Error" and empties every box.

Which box was wrong? What should you type? You have to start again.

A good form keeps what you typed, points at each problem and tells you how to fix it.

Key words

WordWhat it meansExample
ValidationChecking that input is sensible before it is used.
Server sideDone by the app on the server, not in the browser.
DictionaryA collection of keys, each with a value.{"title": "Enter a title."}
Error summaryA box at the top of a form listing every problem.
RedirectTelling the browser to go to another page.
MacroA reusable piece of a Jinja template.

The cells students fill in are left blank in this preview.

By the end of this lesson

Note

I can check form input on the server and show a helpful message for each problem.

Starter: what you already know

Have a go

Starter: what you already know

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Sprint 1, step 5: the goal and stories

PartFor this step
Sprint (a short block of work)Sprint 1: people sign in and handle support requests.
E2.1As a customer, I want to raise a request, so that Netheret knows my problem.
E6.4As any user, I want clear error messages, so that I know how to fix a mistake.

The cells students fill in are left blank in this preview.

The server checks every field

A browser can check a box for you, but anyone can send a form without our page. So the real checks run on the server.

check_request_form looks at each field. It returns a dictionary: the field name is the key, and the message is the value. An empty dictionary means no problems.

A choice, such as priority, must be on the allowed list, even though the page only offers those.

Step 5: the checks

Code: python
# helpdesk/tickets.py (part)
def check_request_form(form, needs_company):
    """Returns a dictionary of {field name: error message}.
    An empty dictionary means there were no problems."""
    errors = {}
    title = form.get("title", "").strip()
    if not title:
        errors["title"] = "Enter a short title for the problem."
    elif len(title) > 150:
        errors["title"] = "The title must be 150 characters or fewer."
    if not form.get("description", "").strip():
        errors["description"] = "Describe the problem."
    # Choices must be on the allowed list, even though the form only offers
    # those: somebody could send any value without using our form.
    if form.get("category") not in CATEGORIES:
        errors["category"] = "Choose a category."
    if form.get("priority") not in PRIORITIES:
        errors["priority"] = "Choose a priority."
    return errors

Make a free account to save your work and track your progress.

Check: server-side validation

Have a go

Check: server-side validation

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your turn: fix the title check

This is the title part of check_request_form, as plain Python. An AI coding assistant wrote the first version. Run it and see what happens with a title of only spaces. Then fix it. Spaces only count as empty. A title over 150 characters gets the second message. Spaces at the start and end are ignored. Write one sentence on what the first version got wrong.

Code: python
def check_title(title):
    # An AI coding assistant wrote this. It only checks for an empty box.
    # Fix it so that:
    #   a title of only spaces counts as empty
    #   a title over 150 characters gets the second message
    #   spaces at the start and end are ignored
    if title == "":
        return "Enter a short title for the problem."
    return ""


print(check_title("Printer will not print"))
print(check_title("     "))

Make a free account to save your work, or press Start lab to work through the whole lesson.

One route shows the form and saves it

The route answers two kinds of request. GET shows the empty form. POST means the form was sent.

On POST, if there are no errors, the ticket is saved. flush() gives it an id, so the reference can be made from it. Then the route redirects to a page that shows the reference. If the user presses refresh there, nothing is saved twice.

If there are errors, the same form comes back, still filled in.

Step 5: the raise a request route

Code: python
# helpdesk/tickets.py (part)
@bp.route("/requests/new", methods=["GET", "POST"])
@role_required("customer", "tier1", "manager")
def new_request():
    is_customer = g.user.role == "customer"
    errors = {}
    form = request.form
    if request.method == "POST":
        errors = check_request_form(form, needs_company=not is_customer)
        if not errors:
            ticket = Ticket(title=form["title"].strip(), status="new", tier=1,
                            # ... description, category, priority, company ...
                            raised_by=g.user)
            db.session.add(ticket)
            db.session.flush()  # gives the ticket its id
            ticket.set_reference()
            db.session.commit()
            return redirect(url_for("tickets.raised", ticket_id=ticket.id))
    return render_template("tickets/new.html", form=form, errors=errors)

Make a free account to save your work and track your progress.

A common mistake

Warning

Many students trust the browser's checks, such as required or maxlength. They help honest users. But anyone can switch them off or send a form without your page. Always check on the server too. The browser's checks are for comfort; the server's are for safety.

Check: saving the request

Have a go

Check: saving the request

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Errors that help, for everyone

Two Jinja macros show the errors. error_summary puts a box at the top, with each problem as a link to its field. field_error puts the message right next to the box that is wrong.

Each field has a hint and a label. aria-describedby tells a screen reader to read the hint and the error. Messages are short, in plain words, and say what to do.

Step 5: one field with its hint

Code: jinja
{# helpdesk/templates/tickets/new.html (part) #}
{{ error_summary(errors) }}
<form method="post" novalidate>
  <div class="field">
    <label for="title">Title</label>
    <span class="hint" id="title-hint">A few words, for example "Printer will not print".</span>
    {{ field_error(errors, "title") }}
    <input type="text" id="title" name="title" maxlength="150" value="{{ form.title }}"
           aria-describedby="title-hint{% if errors.title %} title-error{% endif %}">
  </div>
</form>

Worked example: better error messages

Weak messageHelpful message
Invalid inputEnter a short title for the problem.
Field too longThe title must be 150 characters or fewer.
Error 22Choose a priority.
Company nullChoose the customer's company.

The cells students fill in are left blank in this preview.

Build it yourself: step 5

Build step 5. 1. Write tickets.py with check_request_form and a new_request route for GET and POST. 2. Save the ticket, make its reference and redirect to a confirmation page. 3. Write _macros.html with an error summary and a field error macro, and use them on the form with labels, hints and aria-describedby. 4. Test by hand. Send it empty, then with a 151 character title. Then send a priority that is not on the list, changed in the browser's tools. 5. Commit and write the change log row.

A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.

Make a free account to save your work, or press Start lab to work through the whole lesson.

Compare with the step 5 code

Tip

Compare yours with the step 5 code on GitHub. Look at _macros.html: the two macros are used by every form after this.

Change log entry for step 5

DateVersion and filesWhat changedWhy
6 Marchstep-05: tickets.py, _macros.html, tickets/new.html, tickets/raised.htmlRaise a request form with server-side checks, an error summary and a reference on a confirmation pageLogging a support request is the first thing the client asked for

The cells students fill in are left blank in this preview.

Next: the request queue

Requests can now come in. In step 6 the help desk sees them in a queue, most urgent first, with filters to find the right ones.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.