我正在尝试验证电话号码是否为数字: -
这是我的user.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
当我第一次在文本字段中输入数字时,它会正确验证,但如果我输入正确的格式然后尝试输入错误的格式,它会跳过验证,我会收到一条消息,表明配置文件已成功更新,但是不保存错误的值(带字母)。
这可能是什么问题?
答案 0 :(得分:11)
我用它,: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 }
同时检查this问题。
答案 1 :(得分:1)
试试这个:
validates_format_of :phone, :with => /\d[0-9]\)*\z/ , :message => "Only positive number without spaces are allowed"