timpone
timpone

Reputation: 19969

validation to disallow a single character (<) in Rails

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.

Upvotes: 0

Views: 290

Answers (2)

Matt
Matt

Reputation: 14048

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.

Upvotes: 2

inyono
inyono

Reputation: 424

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)

Upvotes: 0

Related Questions