Sri
Sri

Reputation: 2273

how can restrict my field should accepts only numbers in rails?

I am using text_field and number_field for one field. This field changes depends upon the question_type selected. The number_field is working fine in chrome. It accepts only number in chrome and not in mozila and IE.

How can I create a method in model or how can i tell that :answer_no should be only numbers(1, 0.1, or any numbers not integers). It should not accept string.

<% if question_type == 'C' %>
  <%= f.text_field :answer_no %>
<% elsif (question_type == 'T') and (question_type == 'F') and (question_type != 'C') and (question_type != 'Y') and (question_type != 'Z') %>
  <%= f.number_field :answer_no %>
<% end %>

Thank you in advance

Upvotes: 0

Views: 5604

Answers (3)

Rahul2692
Rahul2692

Reputation: 344

This is very simple JavaScript function to accept only number in the text field.

Add below JavaScript function

<script type="text/javascript">


  function isNumberKey(evt)
  {
     var charCode = (evt.which) ? evt.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57)) {
         alert("Please Enter Only Numeric Value:");
         return false;
     }

     return true;
  }

And add below code to call JavaScript function to accept only numbers.

<%= f.text_field :zip, :onkeypress=> "return isNumberKey(event)"%>

Upvotes: 2

rails_id
rails_id

Reputation: 8220

You could regex on format :

validates :answer_no, :format => { :with => /^\d+\.?\d*$/ }

test on rubular

If you want to define the question type in the method in model, You can write custom validation function :

  class Model < ActiveRecord::Base
  validate :check_question_type

   protected
   def check_question_type
     if question_type == ....
       validates :answer_no, :format => { :with => /^\d+\.?\d*$/ }
     else
       validates :answer_no,
         :presence => true      
     end
   end
  end

Upvotes: 1

Sri
Sri

Reputation: 2273

Thanks for the Ideas friends. But I made it simple by your ideas.

validates :answer_no, numericality: true, :if => :answer_cannot_be_string?


def answer_cannot_be_string?
  not (question_type.in? %w{ C Y Z })
end

So, Its accepts the decimal and numbers by the question types. I did from the ideas of your answers. So I put +1 to both of you. Thank you.

Upvotes: 0

Related Questions