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?
To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.
The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty. Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity).
Numeric field validation is similar to text field validation, but the conditions compare the value of the number entered to some other value.
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." }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With