Skip to content

Conversation

@jamis
Copy link
Contributor

@jamis jamis commented Jan 30, 2026

Because Mongoid's numeric typecasting functionality differs from that of ActiveRecord, the numericality validator was incorrectly accepting non-numeric strings if allow_blank: true was specified. This PR copies and reimplements Rails' EachValidator#validate method, correctly accounting for this difference between Mongoid and ActiveRecord.

Because Mongoid's typecasting functionality differs from that of Rails,
the numericality validator was incorrectly accepting non-numeric strings
if `allow_blank: true` was specified.
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a bug (MONGOID-5842) where the numericality validator was incorrectly accepting non-numeric strings when allow_blank: true was specified. The root cause is that Mongoid's numeric typecasting behavior differs from ActiveRecord - when a non-numeric string like "asdf" is assigned to a numeric field (Integer, Float, BigDecimal), Mongoid's type casting returns nil rather than keeping the invalid string value. This made the validator incorrectly treat these invalid strings as blank values.

Changes:

  • Reimplements EachValidator#validate in NumericalityValidator to check the raw value before type casting
  • Adds raw_value_for_validation method to retrieve the attribute value before Mongoid's type casting occurs
  • Adds comprehensive test coverage for the fix across Integer, Float, and BigDecimal field types

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

File Description
lib/mongoid/validatable/numericality.rb Overrides the validate method to check raw values before type casting, ensuring non-numeric strings are properly validated even with allow_blank: true. Adds helper method to retrieve raw attribute values.
spec/mongoid/validatable/numericality_spec.rb Restructures and expands test coverage to verify the fix works correctly for Integer, Float, and BigDecimal fields with both allow_blank: false and allow_blank: true options.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@jamis jamis merged commit a0f88c5 into mongodb:master Feb 3, 2026
75 checks passed
@jamis jamis added the bug Fixes a bug, with no new features or broken compatibility label Feb 3, 2026
@jamis jamis deleted the 5842-validates-numericality branch February 3, 2026 21:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Fixes a bug, with no new features or broken compatibility

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants