[英]Client side validations in Rails with forms in a jQuery slider
我有一個網站,它有一個基於 jQuery 的 slider Awkward Showcase 。
在這些幻燈片中,我有一個用於新用戶注冊的 Rails 表單。 我正在使用客戶端驗證 gem進行客戶端驗證。
麻煩的是,因為表單在 second.showcase-slide 上,所以頁面加載時它在 DOM 中不存在,客戶端驗證也不起作用。
我需要一種方法來使用在客戶端驗證的 GitHub 頁面上找到的鈎子,以便在加載我的元素時激活客戶端驗證。
那么如何使用鈎子$('form#user_new[data-validate]').validate();
在我的表單上,它的 id 為user_new
,並且在您更改展示幻燈片時不會立即加載並從 DOM 中消失。
我嘗試了幾個.live
和.bind
變體,但顯然我的 jQuery 非常弱,我沒有運氣。
請幫忙?
我試過這個:
$("body").delegate("#user_username", 'focus', function(){
$('form#user_new[data-validate]').validate()});
但是現在每次我單擊#user_username 字段時,都會將另一個驗證添加到堆棧中,並且我會為單個字段顯示多個錯誤(克隆)。
好的,這就是我想出的,但它肯定是丑陋的。 歡迎任何更好的解決方案!
$("body").delegate("#user_username", 'focus', function(){
if ($('form#user_new[data-validate]').data('events') === undefined ) {
$('form#user_new[data-validate]').validate()
}});
我正在使用 rails 3.2.8、simpleForm 2.0.2、client_side_validations 3.2.0.beta.4 和 client_side_validations-simple_form 2.0.0.beta.1 並且上述解決方案運行良好,但解決方案不完整,因為當驗證是反彈(您更改選項卡並返回)如果您多次觸發具有相同字段的相同表單中的錯誤,則字符串錯誤將重復,三倍,等等。
因此,對於這個特定字段,您必須在 js.coffee 文件中添加一個“跨度橡皮擦”,因為 client_side_validations 每次都會添加一個跨度,而您只想看到最后一個。
完整的解決方案是(將代碼放入您的 *.js.coffee 文件):
# the above suggested works well
$("body").delegate "#user_name", "focus", ->
$(this).closest("form").removeClass("validateme").validate()
# my additional code
$("#user_username").live "blur", ->
$(@).siblings("span:not(:last)").remove()
# $(@).siblings() is identical to $(@).parent().children() except @
# in other words, select my "brothers" except me if yes or not match the selector
# (nicer!)
這是一個例子; 如果您的情況不同,請檢查生成的 HTML 並使用選擇器。
這可能不那么厚實。
不過,您需要將 class(即“validateme”)添加到您關注的領域。
$("body").delegate("#user_username.validateme", 'focus', function(){
$(this).closest('form').removeClass('validateme').validate();
});
這樣,僅當關注的元素具有 validateme class 時才添加驗證。 一旦它被聚焦,class 就會被刪除,並且驗證會應用於表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.