unanchored-format-validation
A format validation whose pattern uses ^ or $, which match at any line.
- Group
- Code
- Runs
- Runs under ur scan:
ur scan --rule unanchored-format-validation - Level
- warning
- Reads
- Every file
- Fix
- None: whether a pattern means to match each line is the author's to say
Why
Ruby's ^ and $ match at the start and end of every line, not of the whole string, so validates :name, format: { with: /^[a-z]+$/ } accepts "admin\n<script>alert(1)</script>": the first line matches, and the rest is saved with it. Anchor the pattern with \A and \z, which match only at the start and end of the value; Rails itself raises for a format: pattern with ^ or $ unless multiline: true is given.
The fix, as Ur suggests it: anchor the pattern with \A and \z.
For agents
Anchor a format validation's pattern with \A and \z, never ^ and $.
Example
app/models/user.rbclass User < ApplicationRecord
validates :name, format: { with: /^[a-z]+$/ }
end
$ ur scan --rule unanchored-format-validation
warning[unanchored-format-validation]: `/^[a-z]+$/` starts with `^`, which matches after any newline
--> ./app/models/user.rb:2:30 `with: /^[a-z]+$/`
= hint: anchor the pattern with `\A` and `\z`
= see: Securing Rails Applications, 7.6 Regular Expressions, Rails Guides (2025-10-01), https://guides.rubyonrails.org/security.html#regular-expressions
scanned 1 file (no framework recognized)
unanchored-format-validation: 1 high, 0 medium
1 finding and 0 of medium confidence
Source
Securing Rails Applications, 7.6 Regular Expressions, Rails Guides (2025-10-01).