我有一个动态输入列表,用于获取用户的名称。我需要使用 jquery 验证插件进行验证。以下是我的代码结构。
我浏览了所有 SO 问题但未能得到适当的解决方案。
jquery verify 不支持此验证数组,或者我缺少任何完成该任务的代码。
投票反对的人,感谢你们的服务。
const users$ = jQuery("form.users");
const btnAddRow = jQuery("button.btn-add-row");
btnAddRow.on('click', function(){
const trs$ = users$.find('table tbody tr');
const len = trs$.length;
let html = ` <tr>
<td><input type="text" name="user[${len}][name]" /></td>
</tr>`;
users$.find('table tbody').append(html);
setTimeout(()=>{ // Executed whenever there is addition of row
setValidationRule();
})
})
var allInputBox = {};
// Executed on default
setValidationRule();
function setValidationRule(){
//looping through all inputs
jQuery("input[name*='user[']").each(function() {
allInputBox[jQuery(this).attr('name')] = {
required: true //add more params if needed.
} //pushing in array
})
}
users$.validate({
rules: {
"username":{
required: true
},
...allInputBox
},
submitHandler:function(form, event){
event.preventDefault();
event.stopPropagation();
console.log("passed");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<form class="users">
<input type="name" name="username">
<button class="btn-add-row" type="button">Add Row</button>
<table>
<tbody>
<tr>
<td><input type="text" name="user[0][name]" /></td>
</tr>
<tr>
<td><input type="text" name="user[1][name]" /></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
编辑 1:按照@swati 的回答,动态创建一行,不应用验证规则