gpt4 book ai didi

javascript - jquery 使用多个 if/else 条件验证规则

转载 作者:行者123 更新时间:2023-12-03 06:24:40 25 4
gpt4 key购买 nike

我想使用 jQuery validate() 规则来处理 2 个交叉字段。如果在其中一个字段中输入,则另一个字段也是必需的。此外,一旦需要,数字字段的格式应为第 15 位数字应为整数,日期字段应为 mm/dd/yyyy格式和日期应小于今天的日期。

//..

$("#adjustmentsFormID").validate({
rules: {
refTranNbr: "required",
refTranDate: "required"
},
messages: {
refTranNbr: {
required: function (element) {
if ($("#refTranDate").val().length > 0) {
return "Please enter the reference transaction number ";
} else if (!refNumChk($("#refTranNbr").val())) {
return "Please enter a valid Reference Transaction Number";
} else {
return false;
}
}
},
refTranDate: {
required : function (element) {
var tdate = $("#refTranDate").val();
if ($("#refTranNbr").val().length > 0) {
return "Please enter a date for the Refering Transaction to complete this transaction.";
} else if ((new Date() > new Date(tdate))) {
return "Please enter a reference transaction date less than today's date.";
} else {
return false;
}

}
},
});


..//

在这两种情况下,第一个条件都是所需的现场工作。然而,对于refNum字段具有 refNumChk 的第二个条件不管用。实际上它没有被调用。同样,对于 refTranDate 所需的字段验证也有效 date > tDate没有被检查。不确定这个方法是否有效,或者我应该针对多种情况做不同的事情。

最佳答案

您的 jQuery 验证方法是错误的,messages 用于在验证错误时仅返回错误消息。

因此您所做的唯一验证是必需的验证,您可以添加自定义验证规则来解决此问题

jQuery(function($) {
jQuery.validator.addMethod("refNumChk", function(value, element, params) {
return this.optional(element) || /^\d{15}[A-Z]$/.test(value);
}, jQuery.validator.format("Enter a value in forat aa-999"));
jQuery.validator.addMethod("lessThanToday", function(value, element, params) {
return this.optional(element) || new Date() > new Date(value);
}, jQuery.validator.format("Value should be less than today"));


$("#adjustmentsFormID").validate({
rules: {
refTranNbr: {
required: true,
//refNumChk: true
pattern: /^\d{15}[A-Z]$/
},
refTranDate: {
required: true,
lessThanToday: true
}
},
messages: {
refTranNbr: {
required: "Please enter the reference transaction number",
pattern: "Please enter a valid Reference Transaction Number"

},
refTranDate: {
required: "Please enter a date for the Refering Transaction to complete this transaction.",
lessThanToday: "Please enter a reference transaction date less than today's date."
},
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="adjustmentsFormID" method="post" action="">
<div>
<input name="refTranNbr" />
</div>
<div>
<input name="refTranDate" />
</div>

<input type="submit" value="Save" />
</form>

关于javascript - jquery 使用多个 if/else 条件验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38711303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com