Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
Dev R Avatar asked May 09 '12 11:05

Dev R


People also ask

How can I check mobile number in regex?

/^([+]\d{2})? \d{10}$/ This is how this regex for mobile number is working. + sign is used for world wide matching of number.

How do you validate a regex pattern?

RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.

Can you use regex on numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.


1 Answers

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.

like image 111
beck03076 Avatar answered Sep 18 '22 19:09

beck03076