Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a good practice to use regular expression for input validation?

Currently I have some theoretically background in regular expression, but I have almost never used them.

I am trying to develop some classes for general input validation, and I have being writing methods without any use of regular expressions. I recently read this Jeff's article, and now I am wondering if I should refactor some of the methods to include regexp inside them.

I thought that regular expressions were used to build front-ends for applications like parsers and anything else, but apparently they are used for much more than that.

I realize that not all validations can or should be done with regular expressions, but are they a good practice to validate inputs?

like image 827
eKek0 Avatar asked Apr 18 '09 22:04

eKek0


3 Answers

Regular expressions are just one way to match text against a pattern. There are other ways to do the same thing without using a regex. You shouldn't think of regular expressions as a buzzword that you must include in your code. Use whatever tool works the best.

For input validation just be sure whatever tools you're using let you specify exactly what kind of text you want to accept and reject everything else by default. Regular expressions let you do this easily and concisely for certain kinds of input, which is why many people use them.

like image 117
Brian Carper Avatar answered Nov 03 '22 16:11

Brian Carper


Yes!

Regular expressions usually let you build a pretty solid input validation that's fairly readable in a very short space of time.

Something that does the right job, is maintainable and lets you get onto other things is good in my books.

As always, apply common sense and if a regex is a bad tool for the job, don't use it.

like image 24
Artelius Avatar answered Nov 03 '22 14:11

Artelius


Using regexp validation is a good idea provided that you don't branch off into applying more than besic regular expressions:

If you find yourself validating potentially complex structures such as Michael Ash does in his attempt to verify a date you are off the beaten path and asking for trouble:

^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[13-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

Your code will suffer maintenance problems.

like image 35
ojblass Avatar answered Nov 03 '22 16:11

ojblass