9

我正在尝试验证电话号码是否为数字:-

这是我的用户.rg

 number_regex = /\d[0-9]\)*\z/


 validates_format_of :phone, :with =>  number_regex, :message => "Only positive number without spaces are allowed"

这是我的 view.html.haml

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

这是控制器

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

当我第一次在文本字段中输入数字时,它会正确验证,但如果我输入正确的格式,然后尝试输入错误的格式,它会跳过验证,并且我会收到一条消息,说明配置文件已成功更新,但是不保存错误值(带字母)。

这里可能是什么问题?

4

2 回答 2

18

我用这个,:with =>“没问题”。

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

如果你想要一条消息,(不是按摩),试试这个,

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

还要检查这个问题。

于 2012-05-09T12:40:23.943 回答
2

尝试这个:

    validates_format_of :phone, :with =>  /\d[0-9]\)*\z/ , :message => "Only positive number without spaces are allowed"
于 2012-05-09T12:48:46.203 回答