Validate: Only letters, numbers and - - ruby-on-rails

I would like to validate my users, so they can only use a-z and - in their username.
validates_format_of :username, :with => /[a-z]/
However this rule also allows spaces ._#
Username should use only letters, numbers, spaces, and .-_# please.
Any ideas?
Best regards.
Asbjørn Morell

You may need to say the whole string must match:
validates_format_of :username, :with => /^[-a-z]+$/
You may also need to replace ^ with \A and $ with \Z, if you don't want to match a newline at the start/end. (thanks to BaroqueBobcat)
Appending an i will cause it to match in a case-insensitive manner. (thanks to Omar Qureshi).
(I also originally left off the +: thanks to Chuck)

More complex solution but reusable and with more fine grained error messaging.
Custom validator:
app/validators/username_convention_validator.rb
class UsernameConventionValidator < ActiveModel::EachValidator
def validate_each(record, field, value)
unless value.blank?
record.errors[field] << "is not alphanumeric (letters, numbers, underscores or periods)" unless value =~ /^[[:alnum:]._-]+$/
record.errors[field] << "should start with a letter" unless value[0] =~ /[A-Za-z]/
record.errors[field] << "contains illegal characters" unless value.ascii_only?
end
end
end
(Notice it does allow ' . - _ ' and doesnt allow non ascii, for completeness sake)
Usage:
app/models/user.rb
validates :name,
:presence => true,
:uniqueness => true,
:username_convention => true

The [] may contain several "rules" so [a-z0-9] gives lowercase letters and numbers
the special character - must go at the start of the rule
Does
[-a-z0-9#_.]
give the effect you want?

validates_format_of :username, :with => /^[\w\-#]*$/
Note the *, which means '0 or more'

Simply change the regular expression to match all characters your specification states (\w covers all alphanumeric characters -- letters and numbers -- and an underscore).
validates_format_of :username, :with => /[\w \.\-#]+/

Validation to allow letters and whole numbers only:
/\A[a-zA-Z0-9]+\z/

Related

How to validate text input so that it only allows a-z, A-Z, 0-9, ();:?!,.[]{}- characters(also space) and in Rails?

How to validate text input so that it only allows a-z, A-Z, 0-9, ();:?!,.[]{}- characters(also space)?
I added something like in my model
class Oder < ApplicationRecord
......
......
validates :text, presence: true, format: { with: /[0-9\w]*[\(\;\:\-\?\!\,\.\[\]\{\}\,\.)]*/ }
......
end
end
But it is not working. It allows other characters(wïth ûmlauts) also.
Thanks in advance.
At the moment the regexp matches when one or more characters are in your text somewhere. You need to change the regexp to only match when the characters are the only characters between the start of the string (\A) and its end (\z).
Change your regexp to:
/\A[0-9\w\s\(\;\:\-\?\!\,\.\[\]\{\}\,\.)]*\z/
validates_format_of :text, without: /[-0-9\w ;:,.?!\[\]{}()]*/

How can I include Polish letters in a validation regex?

I have validation for first_name:
validates :first_name, :format => {:with => /\A[a-zA-Z]+\z/}
Can somebody tell me how to add letters like:
ą,ż,ź,ć,ń,ł,ś,ę,ó, Ą,Ż,Ź,Ć,Ń,Ł,Ś,Ę,Ó
I think you need Oniguruma character classes. To verify that string consists of unicode letters, use alpha character class.
"abcÓ" =~ /\A[[:alpha:]]+\z/ # => 0
"abcÓ1" =~ /\A[[:alpha:]]+\z/ # => nil # contains digit
This, of course, will include not only said polish letters, but all unicode letters. Including japanese kana, for example (おにぐるま).

Rails custom validation based on a regex?

I have the following regex that I use in my routes.rb for /type-in-something-here
# A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _
# At least 5, no more than 500 characters
In the routes this works well as:
match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/ }
I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb:
validates_format_of :uuid, :with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i, :message => "Invalid! Alphanumerics only."
But this validates_format_of isn't working, and instead of adding an error it's allow the record to save.
Any ideas what's wrong?
Thanks
For validation purposes, remember to add the beginning and end of string markers \A and \Z:
validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i
Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)
using something like this
validates :uuid, :format => {:with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i},
:message => "your message"
For more check this
validates :name, format: { with: /\A[a-zA-Z]+\z/,
message: "Only letters are allowed" }

Rails Validations, number + letters + spaces

Looking for a Rails validation that will only allow letters, numbers, and spaces.
This will do letters and numbers, but no spaces.
I need spaces.
validates_format_of :name, :with => /^\w+$/i,
:message => "can only contain letters and numbers."
validates_format_of :name, :with => /^[a-zA-Z\d ]*$/i,
:message => "can only contain letters and numbers."
Here is only Number, Letters ans spaces.
Is that exactly what you need ?
PS : This tools is very useful if you are doing a lot of reg-exp : http://rubular.com/
This is one way:
validates :name, format: { with: /\A[a-zA-Z0-9\s]+\z/i, message: "can only contain letters and numbers." }
Have a nice day.
If you only want letters, numbers, and spaces, but not underscores, the accepted answer won't work for you. The following also won't allow empty strings, but it wouldn't matter either way if the rails model has validates_presence_of :name
/^[a-z0-9 ]+$/i

Validate that string belongs to specific language alphabet

How can I validate Rails model string attribute that it belongs to specific language alphabet characters?
Thanks.
There's a library called whatlanguage that recognize the languages of the string, example:
require 'whatlanguage'
"Je suis un homme".language # => :french
Works with Dutch, English, Farsi, French, German, Swedish, Portuguese, Russian and Spanish out of the box, so it recognize Cyrillic too.
You'll want to validate the value of the attribute against a regular expression.
# Only match characters a-z
validates_format_of :attr, :with => /[a-z]/
validates_format_of seems to be the right thing for you. the documentation says:
Validates whether the value of the specified attribute is of the correct form by matching it against the regular expression provided.
class Person < ActiveRecord::Base
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
end
Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
A regular expression must be provided or else an exception will be raised.

Resources