表单在提交前使用jquery验证



我有一个选项列表,我必须证明至少应该有4个选项。

我已经粘贴了该表单的一部分:

$("#livechatform").validate({
rules: {
options[]: {
required: true,
minlength: 4
}
},
messages: {
options[]: {
required: "Please enter at least 4 options",
minlength: "Please enter at least 4 options"
}
},
submitHandler: (form) => form.submit();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="custom-validation repeater" method="post" id="livechatform" enctype="multipart/form-data" action="/admin/poll/create">
<div class="col-10">
<input class="form-control" name="options[]" type="text" required>
</div>

<div class="d-flex flex-wrap gap-2 mt-3">
<button type="submit" class="btn btn-primary waves-effect waves-light">
Submit <span class="spinner-border spinner-border-sm"></span>
</button>

<button type="reset" class="btn btn-secondary waves-effect">
Cancel
</button>
</div>
</form>

但是它不工作。有谁能帮我一下吗?

First:你需要包含jQuery验证插件


在你的JS代码中有两个问题:输入的名称是一个字符串,因此它需要在引号中:

'options[]': {...

submitHandler结尾的分号是错误的-删除它。我发现了这两个问题,因为我在控制台中读取了错误消息…

此外,您需要在输入数组中定义索引:

<input name="options[0]" type="text">
<input name="options[1]" type="text">
<input name="options[2]" type="text">
<input name="options[3]" type="text">

,然后用选择器[name^="options"]为每个输入添加规则,这意味着:每个元素都有一个名称,以"options":

开头
$('[name^="options"]').each(function() {
$(this).rules('add', {
required: true,
minlength: 4,
messages: {
required: "Please enter at least 4 options",
minlength: "Please enter at least 4 characters"
}
})
});

工作的例子:

为了简单起见,我删除了不必要的部分(如id,类或跨度)…

$("#livechatform").validate({
submitHandler: (form) => form.submit()
});
$('[name^="options"]').each(function() {
$(this).rules('add', {
required: true,
minlength: 4,
messages: {
required: "Please enter at least 4 options",
minlength: "Please enter at least 4 characters"
}
})
});
.col {
display: flex;
flex-direction: column;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<form method="post" id="livechatform" action="#">
<div class="col">
<input name="options[0]" type="text">
<input name="options[1]" type="text">
<input name="options[2]" type="text">
<input name="options[3]" type="text">
</div>

<div>
<button type="submit">Submit</button>
</div>
</form>

最新更新