We often validate user input using regular expressions.
There are lots of regular expressions on the Internet. Every now and then we might ‘borrow’ one to save ourselves the life-sapping pain of creating one anew.
However, we should beware.
$ to enclose the regular expression.
# A regular expression matching a # string of lowercase letters /^[a-z]+$/
# A regular expression matching a # string of lowercase letters /\A[a-z]+\z/
Being specific in this case will reduce potential security holes in your code.
$ match the beginning and end of a line, not the beginning and end of an entire string.
If your validations are not precise you could allow potentially dangerous user input to be permitted.
> "word\n<script>run_naughty_script();</script>".match?(/^[a-z]+$/) => true > "word\n<script>run_naughty_script();</script>".match?(/\A[a-z]+\z/) => false
$. You certainly don’t want to let that sort of code to potentially run on your site.
This is a case where being specific is important. Just do it.
photo by Andrew Ridley
Don’t miss my next post, sign up to the One Ruby Thing email and get my next post in your inbox.