如何在jquery.validation中使用其他属性替代name属性完成表单校验
解决方案
jQuery Validate 默认依赖name属性绑定校验规则,你可以通过动态修改输入框的校验规则的方式实现需求,完全不需要修改name属性,具体修改如下:
1. 调整HTML结构
输入框的name属性固定即可,不需要切换修改,同时将单选按钮的name设为相同值实现互斥效果:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script> <div class="radioGroup"> <input type="radio" id="BillIdentitySelect" name="identityType" checked /> <label for="BillIdentitySelect">账单ID</label> <input type="radio" id="NationalCodeSelect" name="identityType" /> <label for="NationalCodeSelect">国籍编码</label> </div> <form> <!-- name固定为BillIdentity,不需要修改 --> <input maxlength="20" name="BillIdentity" id="BillIdentity" class="w-100 text-center" type="text" placeholder="请输入账单ID" /> </form>
2. 修改JS逻辑
不需要修改输入框的name属性,单选切换时动态更新校验规则即可:
// 初始化表单校验 var $form = $("form"); $form.validate(); // 单选切换事件 $("input[type=radio]").click(function () { // 清空原有错误状态和输入值 $("label.error").remove(); $("#BillIdentity").removeClass('error').val(''); var selectedId = $(this).attr("id"); const $billInput = $("#BillIdentity"); // 先移除所有已绑定的校验规则 $billInput.rules("remove"); if (selectedId === "BillIdentitySelect") { $billInput.attr("maxLength", "30") .attr("placeholder", "请输入账单ID") // 新增对应校验规则和提示 .rules("add", { required: true, minlength: 11, messages: { required: "必填项不能为空", minlength: "您需要输入至少11个字符" } }); } else if (selectedId === "NationalCodeSelect") { $billInput.attr("maxLength", "10") .attr("placeholder", "请输入国籍编码") .rules("add", { required: true, minlength: 10, messages: { required: "必填项不能为空", minlength: "号码格式错误!" } }); } }); // 页面加载完成后初始化默认规则 $("#BillIdentity").rules("add", { required: true, minlength: 11, messages: { required: "必填项不能为空", minlength: "您需要输入至少11个字符" } });
可选方案:通过自定义属性绑定规则
如果你需要通过自定义属性(比如data-validate-rule)绑定固定规则,也可以直接在校验初始化时通过自定义选择器匹配:
$form.validate({ // 自定义校验规则匹配逻辑 rules: { BillIdentity: { required: true, minlength: function() { // 读取自定义属性的值作为校验长度 return parseInt($("#BillIdentity").attr("data-min-length")); } } }, messages: { BillIdentity: { minlength: function() { return $("#BillIdentity").attr("data-error-msg"); } } } });
单选切换时只需要修改对应的data-min-length和data-error-msg属性即可,不需要修改name也不需要动态改规则。
内容的提问来源于stack exchange,提问作者Hossein Azizdokht
相关产品推荐
相关产品推荐

