Search code examples
ruby-on-railsruby-on-rails-3.1

Validating the phone number with a regex ruby


I am trying to validate 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 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 field for the first time it validates prperly, but if I enter the correct format and then try to enter the wrong format it skips validations and I get a flash message that profile has been successfully updated, however the wrong value (with letters) is not saved.

What could be the problem here?


Solution

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

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

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

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

    Also check this question.