Validate: Only allow letters, numbers, spaces, hyphens, and apostrophes - ruby-on-rails

I tried doing it like this:
validates :name, :format => { :with => /^[a-zA-Z][a-zA-Z0-9 -']+$/ }
However, it allows ! as well.
How could I change the code so it can only allow letters, numbers, spaces, hyphens, and apostrophes in the name and that it will start with a letter?
Thanks!

You didn't escape the - amid of your regex:
^[a-zA-Z][a-zA-Z0-9 \-']+$
^ here
If you place - inside the character class [](between two characetrs) then you must escape this with escape character(i.e. \). Otherwise it means a range. For your case it was between the space and '. Which means any characters those reside from space(ascii value) to '(ascii value). And unfortunately the ! resides in that range.

Related

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 ?
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 and \d 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/
Error: Regex Construction ..
Invalid range end in character class
\A[[:alpha:]\d->>>HERE>>>'’, ]\z
\d - anything is invalid range because a range operator - cannot
specify a range between a class and anything else.
You'd need to escape the - to make it a literal \A[[:alpha:]\d\-'’, ]\z
or add it to the end or beginning \A[[:alpha:]\d'’, -]\z

rails 4 model text regex allow 0-9, a-z, links and email address

I am working with the following model validation and my tests are working except when I started adding the ability to include links bad characters are making it through :(
validates :application_process,
presence: true,
format: { with: %r{\A[\w\d .,:/-#&?]+\z}, message: :bad_format }
I want to allow the following:
A-Z
a-z
0-9
?
:
/
#
.
,
The regex you have contains a -. A hyphen inside a character class creates a range if it is not escaped and does not appear after a shorthand character class, a range, start or end of the character class.
So, if you need to match a literal hyphen escape it or place at the end of the character class (before ]).
To only match the characters and ranges you specify in the question, use
%r{\A[A-Za-z0-9?:/#.,]+\z}
To add a hyphen:
%r{\A[A-Za-z0-9?:/#.,-]+\z}
^

validates_format_of in rails (only numbers, commas and white spaces)

I have a field "floors" and I want it to accept only numbers, commas and white spaces.
I'm using a validates_format_of :floors, :with => /[0-9\,\s]+/ right now, but it works bad because it accepts a string like "1, 2, abc".
Please help me to find my mistake.
Your regex matches 1, 2, inside 1, 2, abc, it is a partial match. To disallow partial matches, use start-of-string and end-of-string anchors.
In Ruby, to match the start of the string you need to use \A anchor. The end-of-string anchor is \z. Thus, use
/\A[0-9,\s]+\z/
See regex demo
Also note that , is not a special regex metacharacter and does not need escaping.
If you need to start with a number, you can use
/\A\d[\d,\s]*\z/
Here, \d will require a digit to appear in the beginning and then it can be followed with digits, whitespace and commas, zero or more occurrences. Another way of restricting the generic character class is using a lookahead: \A(?=\d)[\d,\s]+\z.
Going further, you can match numbers like 1,300,567.567 or 1 300 567.567 with
/\A\d{1,3}(?:[,\s]\d{3})*(?:\.\d+)?\z/
See another demo

Ruby on rails: Regex to include accented and specials characters?

In my rails app I want to use a regex that accept accented characters(é ç à, ...) and special characters(& () " ' , ...), right now this is my vlidation
validates_format_of :job_title,
:with => /[a-zA-Z0-9]/,
:message => "le titre de l'offre n'est pas valide",
:multiline => true
i want also that regex to not accept non latin characters like Arabic, Chinese, ...
Use [:alnum:] for alphanumeric characters:
validates_format_of :job_title,
:with => /[[:alnum:]]/,
:message => "le titre de l'offre n'est pas valide",
:multiline => true
For the Latin characters you could use the \p{Latin} script character property. You would have to make sure you normalize the input first, as decomposed strings won’t match (i.e. strings containing characters using combining characters). Also this wouldn’t match things like x́ (that’s x followed by COMBINING ACUTE ACCENT) since it won’t compose into a single character, but that’s probably okay as it’s not likely to be actually used by anyone.
For the “special characters” you really need to be more specific about what you want. You say you want to allow " and ' (so called “straight” quotes), but what about “, ”, ‘ and ’ (“typographical” or “curly” quotes”). And since you are allowing European languages, what about «, », ‹, › and „? You could use the \p{Punct} class, which should match all these and more, you will need to decide if it matches too much.
You probably also want to match spaces as well. Will just the space character be okay? What about tabs, non-breaking spaces, newlines etc.? \p{Space} should get them.
There may be other characters you need to match that these won’t pick up, e.g. current symbols, may need to add those too.
So a first attempt at your regex might look like this (I’ve added \A and \z to anchor the start and end, as well as * to match all characters – I think you will need them):
/\A[\p{Latin}\p{Punct}\p{Space}0-9]*\z/
A simple option is to white-list all the characters you want to accept. For example:
/[a-zA-Z0-9áéíóúÁÉÍÓÚÑñ&*]/
Instead of a-zA-Z0-9 you can use \w. It represents any word character (letter, number, underscore).
/[\wáéíóúÁÉÍÓÚÑñ&*]/

Parentheses messing up validation in rails

I have the following validation:
validates_format_of :title,
:with => /^[A-Z0-9 áàâäãçéèêëíìîïñóòôøöõúùûüý'-.]*$/i,
:message => "must contain only letters, numbers, dashes, periods, and single quotes"
This works most of the time, but when a title contains an open and closed parentheses, it passes. Anyone know how to get around this or maybe there is something wrong with my validation regex?
At the end of your regular expression you have '-.
This means that you want to allow all characters between (and including) the apostrophe and the period just like you did at the beginning of the regular expression with A-Z and 0-9.
The expression /['-.]/ allows all these characters: '()*+,-.
Inside the [], you need to escape the - character. I think that this will work the way you are hoping:
/^[A-Z0-9 áàâäãçéèêëíìîïñóòôøöõúùûüý'\-.]*$/i
PS. You don't have to escape the . inside the square brackets []

Resources