高级JQuery验证:避免某些条件的验证

前端之家收集整理的这篇文章主要介绍了高级JQuery验证:避免某些条件的验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在制作一个表单,我正在使用( http://docs.jquery.com/Plugins/Validation/)的惊人的JQuery验证插件.

此表格允许人们进行捐赠并指定他们是否将通过支票或信用卡付款.我使用单选按钮显示信用卡asp面板或检查asp面板.

我的规则和信息都有效.但是,我希望创建一个规则,避免根据另一个因素(信用卡面板的可见性设置为“隐藏”)验证表单的某些部分(信用卡面板).

请原谅我即将淹没你的代码 – 我删除了大部分不相关的部分,只留下那些展示我的方法的人.

我的body_onload javascrip方法

@H_502_10@function body_onload() { document.getElementById('<%=Cheque.ClientID %>').style.display = 'none'; document.getElementById('<%=CreditCard.ClientID %>').style.display = 'none'; }

我的单选按钮用于选择付款方式:

@H_502_10@<div style="width:430px; padding:5px;"><b>Payment Method:</b>&nbsp;&nbsp; <input type="radio" name="PaymentMethod" value="Cheque" onclick="ShowPaymentPanel(this.value)"/>Cheque &nbsp;&nbsp;&nbsp;<input type="radio" name="PaymentMethod" value="CreditCard" onclick="ShowPaymentPanel(this.value)"/>Credit Card</div>

我冗长的验证方法

@H_502_10@$(document).ready(function(){ jQuery.validator.addMethod("phoneUS",function(phone_number,element) { phone_number = phone_number.replace(/\s+/g,""); return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); },"<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please specify a valid phone number"); // validate form on keyup and submit $("#TransactionForm").validate({ rules: { FirstName: "required",LastName: "required",Phone: { required: true,phoneUS: true },CCName:{ required: true },CCNumber:{ required: true,creditcard: true },CCExpiry:{ required: true,digits: true,minlength: 4,maxlength: 4 } },messages: { FirstName: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;required",LastName: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;required",Phone: {required: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;required"},CCName: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter the name on the card",CCNumber: { required: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter the card number",creditcard: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter a valid card number" },CCExpiry: { required: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter the expiry date",minlength: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter as MMYY",maxlength: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please enter as MMYY",digits: "<br/>&nbsp;&nbsp;&nbsp;&nbsp;Date must be numeric" } } }); });

任何帮助将不胜感激!

解决方法

验证插件允许这样做,对于必需属性,您不限于true / false,您可以在规则中执行此操作: @H_502_10@CCNumber:{ required: "#<%=CreditCard.ClientID %>:visible",creditcard: "#<%=CreditCard.ClientID %>:visible" }

此外,如果由于某种原因不受限制,您可以缩短onload中的其他语法:

@H_502_10@$(function() { $("#<%=Cheque.ClientID %>").hide(); $("#<%=CreditCard.ClientID %>").hide(); });

但是,我建议对它们应用“隐藏”的CSS样式以避免任何可能的闪烁,然后只使用$(“#<%= Cheque.ClientID%>”).show();当你做什么时触发它的语法来显示它们.无论你采用什么方法,那么:可见选择器将起作用,它的行为与听起来完全一样.

原文链接:https://www.f2er.com/jquery/180957.html

猜你在找的jQuery相关文章