0

I'd like to disallow the < character in first_name in our model. What would the regex for this be?

I tried

  validates :first_name, format: { with: /[^<]/ }

but doesn't seem to work.

timpone
  • 19,235
  • 36
  • 121
  • 211
  • Slightly more correct is `\A` instead of `^` - `\A` is for start of string rather than start of line (even though they should be the same here). https://ruby-doc.org/core-2.5.1/Regexp.html#class-Regexp-label-Anchors – Dave Slutzkin Jan 18 '19 at 18:43
  • 1
    @DaveSlutzkin the `^` in this case has nothing to do with start of line it is an exclusionary character class e.g. any character except `<` – engineersmnky Jan 18 '19 at 19:54
  • While one could answer this question as `with: /\A((?!<).)*\z/` [This SO Post](https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word) offers a much better explanation than I would have – engineersmnky Jan 18 '19 at 20:05
  • @engineersmnky Oh yeah! I'm an idiot. – Dave Slutzkin Jan 18 '19 at 21:27

2 Answers2

2

You can use without instead of with in the validation
You may want to escape the less-than, as zishe suggests, but I don't think this is necessary.

validates :first_name, format: { without: /</ }

https://guides.rubyonrails.org/active_record_validations.html#format

edit: incorporated @engineersmnky points, much simpler.

Matt
  • 13,948
  • 6
  • 44
  • 68
  • The "hat" inside a character class means any character **Not** in this class. However the OP's validation will only fail if the **Only** character is `"<"` – engineersmnky Jan 18 '19 at 19:53
0

You are currently only capturing the first character. So you probably want to do something like [^<].* (a string starting with anything but < and followed by arbitrary characters)

inyono
  • 424
  • 2
  • 6