M Ahmed
M Ahmed

Reputation: 129

Numerical validation not accepting 0 as a number

I have a contact number, and would like to validate it so it is 11 digits long. I'd like it to accept 01234567891.

I'm using a validation:

validates :contactNo,
          :length => {
                      :is => 11,
                      :format => { with: /[0-9]+/ },
                      :greater_than_or_equal_to => 0,
                      :message => "Contact number is not valid"
                     }

It doesn't accept 0 as a digit.

How would I get around this?

Upvotes: 2

Views: 547

Answers (2)

max
max

Reputation: 102318

You can solve the validation with just a regular expression by using an exact number instead of +

validates :contactNo, format: /[0-9]{11}/, message: 'must be eleven digits (0-9)'

But as noted by @Nathan you cannot use an integer field as 01 is typecast to 1 as an integer.

Upvotes: 2

Nathan
Nathan

Reputation: 8036

Saving as an integer will cause ActiveRecord to typecast it, which will drop the leading 0, which will make the actual length 10 instead of 11. If you want leading 0's, you need to save it as a string so that ActiveRecord does not typecast it.

Additionally, you seem to be mixing separate validations in an incorrect way.

Probably you want this:

validates :contactNo,
  :length => {
    :is => 11,
    :message => "Contact number must be exactly 11 digits"
  },
  :format => {
    :with => /[0-9]+/,
    :message => "Contact number can only contain the digits 0-9"
  }

Upvotes: 3

Related Questions