I recently switched to Rails 4 and the security requirements no longer seem to allow the use of regular expressions in the style of /^..$/. The error states that regular expressions should instead be written in the style of /\A..\z/. Making this change seems to resolve all of my server side validation issues, but unfortunately it also broke all of my client side validation in javascript.
A simple example. I want to validate a username to be letters, number, or periods.
The old regex looked like /^[0-9a-zA-Z.]+$/ and worked both server side (Rails 3.x) and client side
new RegExp( /^[0-9a-zA-Z.]+$/ ).test('myuser.name') = true
The new regex looks like /\A[0-9a-zA-Z.]+\z/ and works server side but fails client side
new RegExp( /\A[0-9a-zA-Z.]+\z/ ).test('myser.name') = false
So I'm clearly doing something wrong, but I can't seem to find any explanations. I checked that \A..\z are valid regex to make sure that its not some Rails-specific hack and it seems to be legit.
Any ideas?
JavaScript does not support \A
or \z
in its RegExp
.
Here's some raw data, first for JavaScript:
var a = "hello\nworld"
(/^world/).test(a) // false
(/^world/m).test(a) // true
(/hello$/).test(a) // false
(/hello$/m).test(a) // true
Next, for ruby:
a = "hello\nworld"
a.match(/^world/) # => #<MatchData "world">
a.match(/\Aworld/) # => nil
a.match(/hello$/) # => #<MatchData "hello">
a.match(/hello\z/) # => nil
From this, we see that ruby's \A
and \z
are equivalent to JavaScript's ^
and $
as long as you don't use the multiline m
modifier. If you are concerned about the input having multiple lines, you're simply going to have to translate your regular expressions between these two languages with respect to these matching characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With