ianking
ianking

Reputation: 75

Python dynamic input validation

I have a control structure that looks something like this:

entries = [
    {'sql_col' : 'name', 'display_text' : 'Enter your name: '},
    {'sql_col' : 'email', 'display_text' : 'Enter your email: '},
    {'sql_col' : 'zip', 'display_text' : 'Enter your Zip Code: '},
]

Each entry in the entries list represents a text box that a user will fill in a dialog box. I would like to be able to specify a validation function for each input within that structure, i.e.:

entries = [
    {'sql_col' : 'name', ... , 'validate' : lambda x: return is_name_valid(x)},
    {'sql_col' : 'email', ... , 'validate' : lambda x: return is_email_valid(x)},
    ...
]

Problem is I can't figure out the right syntax to use for something like this. Is my entries syntax correct? How would I call the validation function later in the code and pass it the user's input as a parameter?

Also, best answer is one where I don't need to install any new modules -- I don't have sufficient privileges on the system i'm using to do any installations.

Upvotes: 0

Views: 1050

Answers (1)

abarnert
abarnert

Reputation: 366013

Problem is I can't figure out the right syntax to use for something like this. Is my entries syntax correct?

Have you tried it? The error message you get should immediately tell you that it's not, and point to where it goes wrong, and give any reader who wants to help you a clue to solving it:

{'sql_col' : 'name', 'validate' : lambda x: return is_name_valid(x)},
                                                 ^
SyntaxError: invalid syntax

The problem is that lambda doesn't allow statements, just expressions, and return is a statement. You don't need return in lambda, because it automatically returns whatever the expression evaluates to. So:

{'sql_col' : 'name', 'validate' : lambda x: is_name_valid(x)},

However, it's worth pointing out that lambda x: foo(x) does the exact same thing as just passing foo itself, except more verbosely and more slowly. So, better:

{'sql_col' : 'name', 'validate' : is_name_valid},

How would I call the validation function later in the code and pass it the user's input as a parameter?

You access it the same way you access any other member of a dict—it doesn't matter that it happens to be a function, because functions are perfectly normal values as far as Python is concerned.

And you call it the same you as you call any other function—it doesn't matter that it's an expression rather than a literal name, because expressions that evaluate to a function (or something else callable) are perfectly normal callables as far as Python is concerned.

So:

if entry['validate'](value):
    print('Good value!')

Upvotes: 3

Related Questions