我正在對視圖頁本身進行驗證,因爲我沒有將其存儲在數據庫中。因此,我無法爲此使用模型驗證。我不得不資源使用JavaScript來檢查驗證,以確保用戶沒有提交錯誤的值或提交所需的空字段。這確實可以防止用戶提交錯誤的輸入,但是在錯誤提示框彈出之後,由於某種原因它會禁用提交按鈕,並且用戶無法修復他的錯誤並嘗試再次提交。當使用javascript驗證使用form_tag時的輸入字段時,提交按鈕在rails中停止工作
feedback.html.erb
<script>
function validateForm() {
if (document.forms["myForm"]["name"].value == null || document.forms["myForm"]["name"].value == "") {
alert("Name must be filled out");
return false;
}
if (document.forms["myForm"]["message"].value == null || document.forms["myForm"]["message"].value == "") {
alert("Message must be filled out");
return false;
}
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
<div class="container">
<div class="container-content">
<%= form_tag send_feedback_forms_path, name:'myForm', onsubmit:'return validateForm()' do %>
<%= label_tag 'name', 'Name:', class: 'control-label' %>
<%= text_field_tag 'name', nil, placeholder: 'Enter Your Name', class:'form-control' %>
<%= label_tag 'text', 'Email:', class: 'control-label'%>
<%= email_field_tag 'email', nil, placeholder: 'Enter Your Email', class:'form-control' %>
<%= label_tag 'phone', 'Phone:', class: 'control-label'%> <span style="font-size: small; color: red">(optional*)</span>
<%= phone_field_tag 'phone', nil, placeholder: 'Enter Your Phone Number', class:'form-control' %>
<%= label_tag 'message', 'Message:', class: 'control-label' %>
<%= text_area_tag 'message', nil, placeholder: 'Enter Your Message', class:'form-control' %><br>
<%= submit_tag 'Submit', class: 'btn-primary' %>
<% end %>
</div>
</div>
我以爲你必須有一個數據庫才能使用模型。這就說得通了。謝謝! – myhouse