我在rails中有以下选择标记:
<%= form_tag({:controller => :reports, :action => :monthly_assignments_by_organization_report}, :method => :post, :class=> 'form-horizontal', validate: true) do %>
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="" class="col-sm-4 control-label">Product Type</label>
<div class="col-sm-5">
<%= select_tag 'product_id',
options_from_collection_for_select(Product.all, :id, :name), :include_blank => "Please select...",
class: 'form-control single-select', validate: { presence: true, uniqueness: false }
%>
</div>
<label for="" class="col-sm-4 control-label">Reporting Month</label>
<div class="col-sm-5">
<%= text_field_tag "reporting_month", nil,
class: "form-control reporting-month",
id: "reporting-month",
placeholder: "Select Month"
%>
</div>
<div class="row">
<div class="col-md-4 pull-right align-right">
<%= submit_tag "Generate", class: 'btn btn-primary' %>
</div>
</div>
</div>
</div>
</div>
</div>
<% end %>
我想执行fornt-end表单验证,如果在输入字段中未选择任何选项,则会显示错误消息,这意味着必须选择产品。
我的代码没有模型,所以我无法进行模型验证。它必须是javascript或在视图中。
非常感谢任何提供的帮助。
答案 0 :(得分:0)
了解JQuery Validation或许它符合您的需求
答案 1 :(得分:0)
因此,假设您的标记看起来像:
<select id="product_id" name="product_id">
<option value="Please select...">Please select...</option>
<option value="prod1">Product 1</option>
<option value="prod2">Product 1</option>
<option value="prod3">Product 1</option>
<option value="prod4">Product 1</option>
</select>
<input id="commit" name="commit" type="submit" value="Generate" />
您可以执行以下操作之一。
<强>使用Javascript:强>
var selectElem = document.querySelector("#product_id");
function validateSelect () {
if (selectElem.selectedIndex === 0) {
alert ("Please select a product.");
}
}
selectElem.addEventListener("change", validateSelect);
document.querySelector("#commit").addEventListener("click", validateSelect);
<强>的jQuery 强>
var $selectElem = $("#product_id");
function validateSelect() {
if ($selectElem.prop("selectedIndex") === 0) {
alert ("Please select a product.");
}
}
$selectElem.on("change", validateSelect);
$("#commit").on("click", validateSelect);
演示@ Fiddle