Input Validation with Regular Expressions
November 20, 2008
I have been developing with Django, and it has the ability to validate form inputs based on the type of expected input. Sometimes one may need something more complicated. An example of this would be a Django currency field. They are using regular expressions to make sure that the input is valid.
Taking this idea further, why not always (whenever appropriate) use text for input and then validate it using regular expressions? For example, a form needs email, money, phone number, and zip code. The user enters this data, and behind the scenes the input is treated as simple text. Then during validation regular expressions are used to make sure all data entered is good.
I see this technique as helping to fight against SQL injections in web applications, for instance. Before you even think of parameterized queries and other cool stuff, why not take the step of validating against regular expressions? In this scenario, regex is your first step, and then parameterized queries is the next step. You get defense in depth this way, don’t you?
I don’t claim to be the first to think of this idea. But I do aim to make this technique more popular because there isn’t anything wrong with it, is there? For more information on regular expressions, check out regular expressions.