image by Andrew Ridley
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.
Last updated on June 10th, 2018 by @andycroll
An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.