Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate only numbers

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?

like image 868
John Smith Avatar asked May 07 '17 21:05

John Smith


People also ask

How do I verify a number only?

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.

How do I allow only numbers in a text box?

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.

How do you validate numbers in HTML?

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).

What is numeric validation?

Numeric field validation is similar to text field validation, but the conditions compare the value of the number entered to some other value.


1 Answers

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." }
like image 144
Eric Duminil Avatar answered Oct 11 '22 23:10

Eric Duminil