Jean-Baptiste Jean-Baptiste - 7 months ago 23
Ruby Question

Rails regex syntax error

I am trying to set a regex validation on a form with the code below. I want to allow any alphabetical character, including accents, numbers and hyphen, apostrophe, comma and space. This expression should match the result : "Tir à l'arc, 3d, danse"

validates :interest_list, tags: true, if: lambda { interest_list.any? }
validates :interest_list, format: { with: /\A[[:alpha:]\d-'’, ]\z/, message: "only allows letters, space, hyphen and apostrophe" }


But I have this error empty range in char class: /\A[[:alpha:]\d-'’,]\z/

Can anyone tell me what I'm doing wrong ?

Answer

Any - that appears inside a character class in any position other than the first or last is treated as a range, ie. [0-9] is shorthand for [0123456789]. This range is calculated based on the ASCII values.

You have \d-' in your regex which isn't valid to use for the start/end of a range. Probably what you want is to move - to the start or end of your []

/\A[[:alpha:]\d'’, -]\z/

...and to solve your next problem/question - as it is your regex will only match a single character, you probably also want a repeat on that character class, like a +:

/\A[[:alpha:]\d'’, -]+\z/
Comments