我正在尝试验证此表格。我要确保用户选择至少1位用户并在正文中输入内容。表单使用select2字段和summernote
文本区域。我在做什么错了?
表格:
<form id="ShareThisForm" method="post">
<div class="modal fade" id="Share" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header bg-primary">
<h5 class="modal-title text-light"><i class="fas fa-share-alt mr-1"></i>Share to</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body p-3">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fas fa-user mr-2"></i>Users
</span>
</div>
<select class="form-control select2bs4 select2-hidden-accessible" multiple="" data-placeholder="Share to" tabindex="-1" aria-hidden="true" id="sharing" name="users[]" data-select2-id="sharing">
<?php foreach($this->Database->get('users')->fetchAll() as $user){ ?>
<option value="<?=$user['id']?>"><?=ucwords(str_replace('_',' ',str_replace('.',' ',$user['username'])))?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<textarea class="form-control wysihtml5-alt" name="body"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="ShareThis" class="btn btn-primary"><i class="fas fa-share-alt mr-1"></i>Share</button></div>
</div>
</div>
</div>
</div>
</form>
脚本:
<script>
var select2label
$(document).ready(function () {
$("#ShareThisForm").validate({
rules: {
"users[]": {
required: true,
},
body: {
required: true,
},
},
});
});
</script>
答案 0 :(得分:1)
我相信您正在为select2
多项选择users
使用dropdown
插件。 jQuery validate
将不默认情况下不能与select2
插件一起使用,您需要使用errorPlacement方法来添加必需的field
选择字段下方的消息标签。
我可以看到您也将boostrap
用作模态,因此您也可以使用text-danger
类来确保validation
消息为红色颜色。
如果selected
中的{strong>一无所获,则dropdown
消息将在单击validation
按钮时出现,或者如果是{{1 }},那么我们需要使用submit
插件selected
函数来确保在选择用户后删除了错误标签。我们需要将select2
标签存储为全局变量,以便在做出选择后可以访问该标签以将其删除 OR ,否则再次显示错误消息。
change
在将select2
选项名称属性添加为$('#users').on("change", function(e) {
if (select2label){
select2label.remove(); //remove label
}
});
=> select
时,您需要添加以下验证规则:
array
编辑:正如您现在所提到的,您正在对文本区域使用summernote,并提供了忽略它的参考。我也在答案中添加了users[]
。
实时工作演示:
"users[]": {
required : true
},
ignore: ".note-editor *",