Our search example is still reasonably simple, particularly in terms of its data validation; we're merely checking to make sure the search query isn't empty. Many HTML forms include a level of validation that's more complex than making sure the value is non-empty. We've all seen the error messages on websites:
Please enter a valid e-mail address. 'foo' is not an e-mail address.
Please enter a valid five-digit U.S. ZIP code. '123' is not a ZIP code.
Please enter a valid date in the format YYYY-MM-DD.
Please enter a password that is at least 8 characters long and contains at least one number.
Let's tweak our search()
view so that it validates that the search term is less than or equal to 20 characters long. (For sake of example, let's say anything longer than that might make the query too slow.) How might we do that?
The simplest possible thing would be to embed the logic directly in the view, like this:
def search(request): error = False if 'q' in request...