我希望在提交表单时对其进行验证。我需要检查以下内容:
如果这些条件中的任何一个不匹配,我想在模态窗口中显示错误消息......
我该如何实现这种行为?以下是代码段:
//This function sets max value, based on selected option's data-max
$('select').change(function(e) {
var selectedIndex = $('select').prop("selectedIndex");
var selectedOption = $('select').find("option")[selectedIndex];
$('input[type=number]').attr('max', $(selectedOption).data('max'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="./cart_update.php">
Select Size:
<select size="1" name="options" class="selectsize">
<option value="">-- Select --</option>
<option value="30" data-max="50">30</option>
<option value="31" data-max="50">31</option>
<option value="32" data-max="40">32</option>
<option value="33" data-max="50">33</option>
<option value="34" data-max="50">34</option>
</select>
Quantity
<input type="number" class="cart_qty" name="product_qty" size="1" value="1" min="1" max="100" />
<button class="orange medium full add-to-cart" type="submit">Add To Cart</button>
</form>
&#13;
答案 0 :(得分:1)
由于您没有提供有关您是否在后端验证表单数据的任何信息,我认为您没有。
仅在客户端(即在客户端的webbrowser内)验证表单数据不是可取的。这是因为客户可以轻松地操作您用于验证数据的javascripte代码。通过这样做,可能将欺诈性数据导入您的应用程序(并且可能发生许多更糟糕的事情)。
只有在客户端验证数据时才应使用为用户提供快速反馈,以确定输入的信息是否正确并符合您的定义。在您的应用程序中进一步使用它之前的 之前应该发生在服务器端。
我建议您阅读这些文章,以深入探讨数据验证的主题:
回到你的问题(并假设你阅读了文章,现在只想为了用户的利益而验证数据),这里有一个注释的工作代码片段:
$(document).ready(function () {
// Whenever your form is submitted, execute this function
$('#ourForm').submit(function (e) {
// Prevent the browser from executing the default behaviour -> submitting the form
e.preventDefault();
// Now check the user's entered information for accordance to your definitions
// #1: Check whether any checkbox is ticked
var checkBoxValue = $('#ourCheckbox').val();
// If checkBoxValue is undefined, there is no checkbox selected,
if (!checkBoxValue) {
// There is no checkBox ticked, throw error
alert('Please select a checkbox!');
return false;
}
// #2: Check whether entered value is smaller than the data-max field of the selected checkbox
// Receive the user's entered value
var enteredValue = $('#ourInputfield').val();
// Receive the max value specified by you from the data-max field
var maxValue = $('#ourCheckbox option:selected').attr('data-max');
// If the entered value is bigger than the max-data value
if (enteredValue > maxValue) {
// The entered value is bigger than the data-max field of the selected checkbox, throw error
alert('Your entered value is to large, please choose a value lower than ' + checkBoxValue.value);
return false;
}
// Validating your form data is finsihed, go on with the real work
alert('Your data looks fine, whoooo!');
});
});
这是一个有效的JSFiddle:Web Form Validation: Best Practices and Tutorials (smashingmagazine.com)