gbright
gbright

Reputation: 67

Rails validation: How do you properly validate an invalid non-numeric input on a numeric field?

ActiveRecord apparently will recognize if a non-numeric input is given for a numeric field such as integer or decimal. In these cases, the value is converted to 0 (or 0.0 if a decimal field). Since this occurs before validation, a regex validation meant to detect non-numeric characters such as given below will not work.

validates :fee, presence: true, format: { with: /\A\d{0,11}(\.?\d{0,2})?\z/ }

If a value 'a' is given, it will be saved to the database as 0 and no validation errors will be returned. Although this may be acceptable in many cases, it would be ideal to detect the invalid input and return the validation error to the user.

How can this be done?

Upvotes: 2

Views: 1135

Answers (1)

gbright
gbright

Reputation: 67

I haven't seen any documentation on this so here's the answer I found:

Use numericality: true

This will return a validation error for a non-numeric input on a numeric field.

validates :fee, presence: true, format: { with: /\A\d{0,11}(\.?\d{0,2})?\z/ }, numericality: true

The regex validator will still properly validate any numeric inputs.

Upvotes: 3

Related Questions