簡體   English   中英

Rails:逐步驗證表單字段

[英]Rails: validate form fields step by step

我正在嘗試驗證不同的輸入值。 例如“域名”和“電子郵件”。 兩者都必須具有價值並且必須是唯一的。 所以我嘗試驗證它們

validates :domain,
          :presence => true,
          :uniqueness => { :case_sensitive => true }
validates :email,
          :presence => true,
          :uniqueness => { :case_sensitive => true }

但是當我顯示flash消息時,我得到四個錯誤:

["Domain can't be blank", "Domain has already been taken", "Email can't be blank", "Email has already been taken"]

有可能逐漸檢查它們嗎? 如果輸入字段沒有值,則用戶獲取

["Domain can't be blank"]

但是如果輸入字段具有值且不唯一,則用戶獲取

["Domain has already been taken"]

我該如何實現它?

編輯

下面是打印錯誤消息的代碼:

<% [:error].each do |key| %>
  <% if flash[key] %>
    <div class="<%= key %>" id="flash">
      <%= flash[key] %>
    </div>
  <% end %>
<% end %>

在這里創建錯誤的控制器:

def create

  respond_to do |format|
    # save form data
    @login = Login.new(params[:login])

    # if validation fails, throw error messages
    if !@login.save
      flash[:error] = @login.errors.to_a
    end

    # redirect to landingpage
   format.html { redirect_to :root }

  end

end

如果你沒有先調用@user.valid? flash[:error]會顯示所有錯誤@user.valid? 還是@user.invalid? 然后,它將返回與該@person對象相關的錯誤。

請參閱Rails指南,了解如何使用Flash 還有驗證錯誤部分。

嘗試一下:

if !@login.save       
  flash[:error] = @login.errors.to_a if @login.invalid?
end 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM