0
0
Ruby on Railsframework~5 mins

Numericality validation in Ruby on Rails

Choose your learning style9 modes available
Introduction

Numericality validation checks if a value is a number. It helps keep data clean and correct.

When you want to make sure a user's age is a number.
When a price field must only accept numbers.
When counting items and you need whole numbers.
When validating scores or ratings that must be numeric.
Syntax
Ruby on Rails
validates :attribute_name, numericality: true

Replace :attribute_name with the name of the field you want to check.

You can add options like only_integer: true to allow only whole numbers.

Examples
Checks that age is a number (integer or float).
Ruby on Rails
validates :age, numericality: true
Ensures quantity is a whole number without decimals.
Ruby on Rails
validates :quantity, numericality: { only_integer: true }
Validates price is a number greater than zero.
Ruby on Rails
validates :price, numericality: { greater_than: 0 }
Makes sure score is a number not bigger than 100.
Ruby on Rails
validates :score, numericality: { less_than_or_equal_to: 100 }
Sample Program

This example defines a Product model with two validations:

  • price must be a number greater than zero.
  • stock must be a whole number zero or more.

We create a product with invalid values to see the error messages.

Ruby on Rails
class Product < ApplicationRecord
  validates :price, numericality: { greater_than: 0 }
  validates :stock, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
end

product = Product.new(price: -5, stock: 3.5)
product.valid?
product.errors.full_messages
OutputSuccess
Important Notes

Numericality validation works only on attributes that respond to to_f or to_i.

Use allow_nil: true if you want to skip validation when the value is empty.

Validation error messages can be customized for better user feedback.

Summary

Numericality validation ensures values are numbers.

You can restrict to integers or set limits like greater than or less than.

This helps keep your data accurate and prevents mistakes.