解决validate无法验证多个相同name的input Published on Jan 5, 2021 in Java教程 with 0 comment JS **解决validate无法验证多个相同name的input (动态生成的表格)** 记录实际业务遇到问题 # 首先给input分别设置不同的id ```javascript //用于生成uuid function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } function guid() { return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); } //为动态添加的元素绑定事件 $('#contentTable').on('click', '.addTable', function () { // var uuid = "qty" + guid(); //步骤预设 var str1 = ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' +\n' + ' -\n' + ' \n' + ' '; $('#contentTable > tbody:nth-child(2)').append(str1); }); ``` # 设置validate的多个input验证方法为根据id验证 ```javascript $(function () { if ($.validator) { $.validator.prototype.elements = function () { var validator = this, rulesCache = {}; return $([]).add(this.currentForm.elements) .filter(":input") .not(":submit, :reset, :image, [disabled]") .not(this.settings.ignore) .filter(function () { var elementIdentification = this.id || this.name; !elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this); if (elementIdentification in rulesCache || !validator.objectLength($(this).rules())) return false; rulesCache[elementIdentification] = true; return true; }); }; } # [id^=qty] 根据实际业务需求修改 id以qty开头的 $('[id^=qty]').each(function (e) { $(this).rules('add', { minlength: 2, required: true }) }); }); ``` 本文由 admin 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。