>我有两个字段,名称和ID保存金额和购买金额。我需要一个,并且只需要填写一个字段,并具有有效的货币金额。
我有验证货币金额的代码,并对字段名称进行了分组,以便错误出现在正确的位置。我需要扩展代码,以便错误也将显示填充两个字段的位置,或者当两个字段都没有填充时。
<script>
jQuery.validator.addMethod(
"money",
function(value, element) {
var isValidMoney = /^d{0,4}(.d{0,2})?$/.test(value);
return this.optional(element) || isValidMoney;
},
"Please enter a valid amount"
);
$("#myForm").validate({
rules: {
saveamount: {
money: true,
},
buyamount: {
money: true,
}
},
groups: {amountgroup: "saveamount buyamount"},
errorPlacement: function(error, element) {
if (element.attr("name") == "saveamount" || element.attr("name") == "buyamount" ) {
error.insertAfter("#buyamount");
} else {
error.insertAfter(element);
}},
messages: {
saveamount: "Please enter a valid monetary amount in one field only.",
buyamount: "Please enter a valid monetary amount in one field only."
}
});
</script>
您可以使用
require_from_group
并定义组中的字段数是否完整。
jQuery.validator.addMethod(
"money",
function(value, element) {
var isValidMoney = /^d{0,4}(.d{0,2})?$/.test(value);
return this.optional(element) || isValidMoney;
},
"Please enter a valid amount"
);
$( "#myform" ).validate({
rules: {
money: {
money:true,
require_from_group: [1, ".money-group"]
},
buyamount: {
money:true,
require_from_group: [1, ".money-group"]
},
},
submitHandler: function(form,event) {
alert("GO")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<form id="myform">
<label for="money">input1: </label>
<input class="money-group" id="money" name="money">
<br/>
<label for="buyamount">input2: </label>
<input class="money-group" id="buyamount" name="buyamount">
<br/>
<input type="submit" value="Validate!">
</form>