參考來源(使用方式):http://tudip.blogspot.tw/2013/05/jquery-validate-in-rails-applications-by-tudip-technologies.html
doc說明:https://jqueryvalidation.org/validate/
因為我是另外用$.get及jquery-ui的dialog套件相互配合來載入編輯頁面,所以js碼必需寫在被載入的頁面裡,不然其實可以直接寫在coffee檔裡的。
首先,安裝jquery-validation-rails,編輯Gemfile,加上
# validation
gem 'jquery-validation-rails'
執行指令
$ bundle
編輯app/assets/javascripts/application.js檔,加上
//= require jquery.validate
//= require jquery.validate.additional-methods
編輯app/assets/stylesheets/application.css檔,加上
.error {
color: #FF0000;
}
veiw檔及js的部份,需要套入驗證的text_field記得加上:class => "required",js的debug如果打開來的話,表單就算全部驗證通過也不會被送出哦!如果已測試完成,記得要把那行註解掉。
<%= form_for @rcalendar, :url => rcalendars_path do |f| %>
<%= f.hidden_field :v_calendar_id, :value => params[:vid] %>
<div>
<%= f.label :fb_nickname, "Facebook姓名" %><span style="color:#FF0000">(必填)</span>
<%= f.text_field :fb_nickname, :class => "required" %>
</div>
<div>
<%= f.label :fb_urls, "Facebook網址" %><span style="color:#FF0000">(必填)</span>
<%= f.text_field :fb_urls, size: "57", :class => "required" %>
</div>
<div>
<%= f.label :content, "內容" %>
<%= f.text_area :content, size: "50x10" %>
</div>
<div>
<%= f.label :password, "取消預約密碼" %><span style="color:#FF0000">(必填)</span>
<%= f.password_field :password, :class => "required", autocomplete: "off" %>
</div>
<div>
<%= f.label :password_confirmation, "確認取消密碼" %><span style="color:#FF0000">(必填)</span>
<%= f.password_field :password_confirmation, :class => "required", autocomplete: "off" %>
</div>
<%= f.submit "確定" %>
<% end %>
<script type="text/javascript">
$('#new_rcalendar').validate({
//debug: true,
rules: {
'rcalendar[fb_nickname]': {
required: true
},
'rcalendar[fb_urls]': {
required: true,
url: true
},
'rcalendar[password]': {
required: true,
minlength: 5
},
'rcalendar[password_confirmation]': {
required: true,
minlength: 5,
equalTo: "#rcalendar_password"
}
},
messages: {
'rcalendar[fb_nickname]': {
required: '必須填寫'
},
'rcalendar[fb_urls]': {
required: '必須填寫',
url: '請輸入有效的網址'
},
'rcalendar[password]': {
required: '必須填寫',
minlength: '長度不得小於5位數'
},
'rcalendar[password_confirmation]': {
required: '必須填寫',
minlength: '長度不得小於5位數',
equalTo: '密碼不符'
}
}
});
</script>
測試時欄位如果一開始就為空,保持在空值狀態時是不會秀出錯誤的,除非輸入資料後再清空才會有錯誤的提醒,就這點比較讓我匪夷所思,在此提醒一下大家,免得像我一樣一直鬼打牆。