Rails validates_format_of :username - ruby-on-rails

validates_format_of :username, :with => /\A[a-zA-Z_]{2,35}\Z/
I am using the above to validate usernames but I want to change it as it is not good enough for my app. what I need is:
allow letters only or letters with underscore (nothing else)
letters should be all small caps
string does not start or end with underscore (underscore may appear in between letters only)
only one underscore is allowed
username characters limit is 35
I have tried several ways and I could not do it could someone help me out please?

Try following, assuming that "small caps" means lower case:
validates :username, length: { maximum: 35 }, format: { with: /\A[a-z]+_?[a-z]+\z/ }

Related

Regex validation in rails

I am new with rails and I am trying to register my user's names without special characters and spaces but allowing the - symbol.
Example :
##Pierre! => invalid
Pierre-Louis => valid
Pierre Louis => invalid
In the User.rb file I have :
class User < ApplicationRecord
...
validates :first_name, presence: true, length: {maximum: 25}, format: {with: Regexp.new('[^0-9A-Za-z-]')}
...
I don't have any error message and I'm still able to register using special characters.
Also, I'd like to add an error message if the name isn't validated.
Do you have any leads ?
Any help would be much appreciated !
When you validate format with regex, you need to ensure you match the whole string that is being validated. In order to do that your regex needs to start with \A and end with \z that are anchors marking beginning and ending of the string.
In your case:
validates :first_name,
presence: true,
length: {maximum: 25},
format: {with: /\A[-0-9A-Za-z]\z'/}
message: "Custom message"
assuming you accept numbers, small and big letters and a minus sign.

Regexp in format: validation isn't stopping the right characters

I'm new to regex and I'm trying to only allows letters, numbers, quotes and the following characters: !.:?!_+=, -
I have the validation below in a guide modal. I can name a guide just '&' if I want and it accepts it, from my understanding this validation should stop me.
validates :name, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false },
format: { with: /[a-zA-Z 1-9 0!.'":?!_+=, -]/, message: "only allows letters, numbers, quotes and !.:?!_+=, -" }
Not sure what is going wrong, I tested out the regex in Rubular.com and it works in there.
Edit
After testing it, it turns out it stops '&' but lets '&11' pass. If an invalid key is with a valid key it passes. Maybe I'm using format: wrong or shouldn't be using format: for this?
I've simplified a bit your regex, added proper starting/ending line markers and added a + at the end to match if there is one or more char in the input. Here's what it looks like:
/\A[a-zA-Z0-9 !.'":?!_+=,-]+\z/
If you want to have a cleaner one:
/\A[\w !.'":?!_+=,-]+\z/
Since \w matches [a-zA-Z0-9]

Cannot iterate over unique elements

I have an array of errors as below:
n.errors.full_messages
# => ["Password can't be blank", "Password can't be blank", "Password is too short (minimum is 3 characters)"]
I would like to iterate over the unique elements of this array and display them on the screen.
Validation model
class Member < ActiveRecord::Base
has_one :profile
before_save { self.username = username.downcase }
has_secure_password
validates :password, presence: true, length: { minimum: 3 }
end
n.errors.full_messages.uniq do |a|
puts a
end
uniq is not working, and "Password can't be blank" appears twice in my array. Any ideas?
Password can't be blank
Password can't be blank
Password is too short (minimum is 3 characters)
# => ["Password can't be blank"]
Edit: This doesn't actually answer the question, use the answer from #BroiSatse if google brought you here.
The reason you are getting that message twice is because of has_secure_password:
http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password
The first bullet point appears to add validation that makes the password required.
In your model you also add
validates :password, presence: true, length: { minimum: 3 }
The presence: true part of this adds the same validation. Remove this so its:
validates :password, length: { minimum: 3 }
This should fix the problem.
uniqe with a block uses value of the block to compare the elements. What you want is:
n.errors.full_messages.uniq.each do |m|
Anyhow, I think you're approaching the problem from the wrong angle - your problem is not how to avoid displaying duplicate messages, but how this duplication happened.
You could just do a string comparison.
Have the array that is problematic to you. Go over it and save the elements one by one to a new array.
Now when the first one is added to the new array, check that the elements allready in the array don't match the new element to be added. E.g: "My string".eql? "My sting"
There might be of course a more clever way to do this in Ruby. But that would be the idea when doing it in other languages manually.

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: Only letters, numbers and -

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/

Resources