Checking a Ruby Regular Expression Phone Number

I am trying to check if the phone number is a digit or not: -

This is my user.rg

number_regex = /\d[0-9]\)*\z/ validates_format_of :phone, :with => number_regex, :message => "Only positive number without spaces are allowed" 

This is my view.html.haml

 %li %strong=f.label :phone, "Phone Number" =f.text_field :phone, :placeholder => "Your phone number" 

This is the controller

 def edit_profile @user = current_user request.method.inspect if request.method == "POST" if @user.update_attributes(params[:user]) sign_in(@user, :bypass => true) flash[:success] = "You have updated your profile successfully" redirect_to dashboard_index_path else flash[:error] = "Profile could not be updated" render :action => "edit_profile" end end end 

When I enter the number in the text box for the first time, it checks in advance, but if I enter the correct format and then try to enter the wrong format, it will skip the check and I get a message that the profile was updated successfully, but the value is incorrect ( with letters) is not saved.

What could be the problem?

+7
source share
2 answers

I use this :: with => "no problem".

 validates :phone,:presence => true, :numericality => true, :length => { :minimum => 10, :maximum => 15 } 

If you need a message (not MASSAGE) , try this,

  validates :phone, :presence => {:message => 'hello world, bad operation!'}, :numericality => true, :length => { :minimum => 10, :maximum => 15 } 

Also check out this question.

+9
source

Try the following:

  validates_format_of :phone, :with => /\d[0-9]\)*\z/ , :message => "Only positive number without spaces are allowed" 
+1
source

All Articles