In one of my rails models I have this :only_integer validation:
validates :number, presence: true, numericality: { only_integer: true }
This validation also allows inputs like +82938434 with +-signs.
Which validation should I use to only allow inputs without + - only numbers?
The documentation for only_integer mentions this regex :
/\A[+-]?\d+\z/
It means you could just use:
validates :number, format: { with: /\A\d+\z/, message: "Integer only. No sign allowed." }
Rails 7 added :only_numeric option to numericality validator
validates :age, numericality: { only_numeric: true }
User.create(age: "30") # failure
User.create(age: 30) # success
Related
I want to check an integer value in validation. But I want to do it depending on the value of another field. For example, if the width value exists, let it be at least 300 if the width_type is "px", but 30 if the width_type is "rate". How can I do it thanks.
If I understand correctly you are looking for conditional validation
In that case the following should work:
validates :width, numericality: { only_integer: true}
validates :width, numericality: { greater_than_or_equal_to: 300}, if: -> {width_type.to_s == 'px'}
validates :width, numericality: { greater_than_or_equal_to: 30}, if: -> {width_type.to_s == 'rate'}
If you need to handle too many other scenarios I would go with a custom validation like
MIN_WIDTH_PER_TYPE = {px: 300, rate: 30}
validates :width, numericality: { only_integer: true}
validate :_width_with_type
private
def _width_with_type
min_width = MIN_WIDTH_PER_TYPE[width_type.to_sym]
if width < min_width
errors.add(:width, "must be at least #{min_width} when using width type '#{width_type}'")
end
end
You could clean this up further as well but this should point you in the right direction.
This is my code
test 'phonenumber should be 11 digits' do
#user.phonenumber = 11
assert_not #user.valid?
end
this is my model validations, i am using the gem phonelibs
class User < ApplicationRecord
before_save { email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
validates :phonenumber, phone: { possible: true, allow_blank: true }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 256 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
end
this already added the validations because it uses the Google libphonenumber and for Nigeria, it is 11
Phonelib.default_country = 'NG'
but it isnt testing for the exact digits of phone number
You've used a couple of length validations elsewhere - I'd suggest you need the same for your phonenumber field before it will fail validations for being too short.
I.E.
validates_length_of :phonenumber, is: 11
or
validates :phonenumber, length: { is: 11 }
or using a regex:
validates_format_of :phonenumber, with: /[0-9]{11}/
Docs can be found here - hope that helps!
PhoneLib has a lot of extra functionality based on countries and their phone number formats - the best approach here would be to dig properly into that and use their validations based on either a fixed or user-based location.
However, the above should work for ensuring the length of the phonenumber is 11.
Update:
The gem has a number of methods for checking validity of phone numbers, such as the following:
Phonelib.valid? '123456789'
Phonelib.valid_for_country? '123456789', 'XX'
You also need to configure the gem in config/initializers/phonelib.rb - if you could add that code to your question that would be useful.
However, to make use of this, your test could look something like:
test 'phonenumber should be 11 digits' do
#user.phonenumber = 11
assert_not Phonelib.valid?(#user.phonenumber)
end
I am writing a hacker news clone in rails to learn the framework and encountered a problem calling helper methods within a model:
class User < ActiveRecord::Base
has_secure_password validations: false
has_many :posts
validates :name,
presence: { message: username_error_message },
uniqueness: { case_sensitive: false, message: username_error_message },
length: { minimum: 2, maximum: 15, message: username_error_message }
validates :password,
presence: { message: password_error_message },
length: { minimum: 4, message: password_error_message }
private
def username_error_message
"Usernames can only contain letters, digits, dashes and underscores, and should be between 2 and 15 characters long. Please choose another."
end
def password_error_message
"Passwords should be a least 4 characters long. Please choose another."
end
end
I get the following error (Rails 4):
undefined local variable or method `username_error_message' for #<Class:XXX>
You can use constants for the repeated error messages and it will work.
class User < ActiveRecord::Base
has_secure_password validations: false
has_many :posts
USERNAME_ERROR_MESSAGE = "Usernames can only contain letters, digits, dashes and underscores, and should be between 2 and 15 characters long. Please choose another."
PASSWORD_ERROR_MESSAGE = "Passwords should be a least 4 characters long. Please choose another."
validates :name,
presence: { message: USERNAME_ERROR_MESSAGE },
uniqueness: { case_sensitive: false, message: USERNAME_ERROR_MESSAGE },
length: { minimum: 2, maximum: 15, message: USERNAME_ERROR_MESSAGE }
validates :password,
presence: { message: PASSWORD_ERROR_MESSAGE },
length: { minimum: 4, message: PASSWORD_ERROR_MESSAGE }
end
Also, there is a little problem: the error message will be repeated if more than one validation condition fails for every field. One solution is to write a custom validation method, as can be seen here: http://guides.rubyonrails.org/active_record_validations.html#custom-methods
Try using class methods instead:
validates :name,
presence: { message: Proc.new { username_error_message } },
uniqueness: { case_sensitive: false, message: Proc.new { username_error_message } },
length: { minimum: 2, maximum: 15, message: Proc.new { username_error_message } }
validates :password,
presence: { message: Proc.new { password_error_message } },
length: { minimum: 4, message: Proc.new { password_error_message } }
private
def self.username_error_message
"Usernames can only contain letters, digits, dashes and underscores, and should be between 2 and 15 characters long. Please choose another."
end
def self.password_error_message
"Passwords should be a least 4 characters long. Please choose another."
end
The fundamental problem is that you're accessing your methods before they are defined. This problem has nothing per se to do with whether they are private, constants, instance methods or class methods.
The methods are being referenced as your User class is being defined. The references exist within a hash constructor {} being passed as a parameter to the method call validates, which means it is getting evaluated at the time validates is called. It's not like you're passing a block to validates that gets evaluated at a later time.
If you move your definitions to before you reference them, it will address this fundamental problem, but it is also true that you are defining them as instance methods and referencing to them as class methods. You need to bring your mode of definition in line with your mode of access (e.g. by defining the methods as class methods).
(Note: There are a myriad of other options available to you for defining and referencing these strings beyond those noted in the other answers, including class variables, class local variables, etc. They vary primarily in terms where and how they can be accessed. You can even use instance variables and methods, although that would be odd in this case, requiring you to instantiate an object in order to reference them. The point is that Ruby is rich with possibilities and it's well worth investigating/understanding them when you have the time.)
Try this
class User < ActiveRecord::Base
has_secure_password validations: false
has_many :posts
validates :name,
presence: { message: self.username_error_message },
uniqueness: { case_sensitive: false, message: self.username_error_message },
length: { minimum: 2, maximum: 15, message: self.username_error_message }
validates :password,
presence: { message: self.password_error_message },
length: { minimum: 4, message: self.password_error_message }
def username_error_message
"Usernames can only contain letters, digits, dashes and underscores, and should be between 2 and 15 characters long. Please choose another."
end
def password_error_message
"Passwords should be a least 4 characters long. Please choose another."
end
end
private :username_error_message, :password_error_message
I just added some "self." before the methods call to give it a context of this instance.
I also changed the private declaration method
Short of extracting shipping and billing addresses into an Address model, how can I remove this validation duplication?
I only want to validate the billing address if it's not the same as the shipping address. How would I go about extracting it into a module? An example would be really helpful as I never know what to include in modules, or self refers to.
validates :shipping_name, :shipping_address1, :shipping_street_number, :shipping_city, presence: true
validates :shipping_state, inclusion: { in: Address.states.values }
validates :shipping_post_code, length: { is: 5 }, numericality: { only_integer: true }
validates :billing_name, :billing_address1, :billing_street_number, :billing_city, presence: true, unless: -> { self.bill_to_shipping_address? }
validates :billing_state, inclusion: { in: Address.states.values }, unless: -> { self.bill_to_shipping_address? }
validates :billing_post_code, length: { is: 5 }, numericality: { only_integer: true }, unless: -> { self.bill_to_shipping_address? }
You can make a method and then pass in the bits that are different between the two types of addresses. In this case, the difference is the prefix word for the fields and the ability to pass in extra options.
module AddressValidator
def validates_address(type, options = {})
validates :"#{type}_name", :"#{type}_address1", :"#{type}_street_number", :"#{type}_city", {presence: true}.merge(options)
validates :"#{type}_state", {inclusion: { in: Address.states.values }}.merge(options)
validates :"#{type}_post_code", {length: { is: 5 }, numericality: { only_integer: true }}.merge(options)
end
end
class MyModel < ActiveRecord::Base
extend AddressValidator
validates_address(:shipping)
validates_address(:billing, unless: -> { self.bill_to_shipping_address? })
end
Currently I have a function to check if the birthyear is correct:
validates :birth_year, presence: true,
format: {with: /(19|20)\d{2}/i }
I also have a function that checks if the date is correct:
validate :birth_year_format
private
def birth_year_format
errors.add(:birth_year, "should be a four-digit year") unless (1900..Date.today.year).include?(birth_year.to_i)
end
Is it possible to combine the bottom method into the validates at the top instead of the two validates I have now?
You should be able to do something like this:
validates :birth_year,
presence: true,
inclusion: { in: 1900..Date.today.year },
format: {
with: /(19|20)\d{2}/i,
message: "should be a four-digit year"
}
Take a look at: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates
:birth_year, presence: true,
format: {
with: /(19|20)\d{2}/i
}
numericality: {
only_integer: true,
greater_than_or_equal_to: 1900,
less_than_or_equal_to: Date.today.year
}
regex
/\A(19|20)\d{2}\z/
will only only allow numbers between 1900 e 2099
\A - Start of string
\z - End of string