如何使用 jQuery 验证插件验证 Select2 插件数组

How to validate Select2 Plugin array using jQuery validate plugin

我正在尝试验证此表单。我想确保用户至少选择 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>

我相信您正在为 users 多个 selection dropdown 使用 select2 插件。 jQuery validate 不会 使用 select2 插件 默认 你需要使用 errorPlacement 方法来添加一个select 字段下方需要 field 消息标签。

我可以看到你也在使用 boostrap 作为你的模式,所以你也可以使用 class text-danger 来确保 validation 消息在 红色颜色.

如果 nothing 是来自 dropdownselected,则 validation 消息将在单击 submit 按钮时出现,或者如果selected 然后我们需要使用 select2 插件 change 函数来确保我们的错误标签在 select 用户之后被删除。我们需要将 select2 标签存储为全局变量,以便在创建 selection 后可以访问并删除 OR 否则再次显示错误消息.

$('#users').on("change", function(e) {
    if (select2label){
        select2label.remove(); //remove label
    }
});

当您将 select 选项名称属性添加为 array => users[] 时,您需要添加如下验证规则:

"users[]": {
   required : true
},

编辑: 正如您现在提到的,您正在为文本区域使用 summernote,并且您提供了忽略它的参考。我也在我的答案中添加了 ignore: ".note-editor *",

现场工作演示:

//Initiate select2 plugin on users
$('#users').select2()

//global var for select 2 label
var select2label

$(document).ready(function() {
  $("#ShareThisForm").validate({
    ignore: ".note-editor *", //ignore summernote validation
    rules: {
      "users[]": {
        required: true
      },
      body: {
        required: true,
      },
    },
    errorPlacement: function(label, element) {
      if (element.hasClass('select2bs4')) {
        label.insertAfter(element.parent()).addClass('mt-2 text-danger');
        select2label = label
      } else {
        label.insertAfter(element).addClass('mt-2 text-danger');
      }
    },
    submitHandler: function(form) {
      //submit modal form
    },
  });
});

//watch the change on select - if label exist then remove it
$('#users').on("change", function(e) {
  if (select2label) {
    select2label.remove(); //remove label
  }
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#Share">
 Open Modal
</button>

<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="'.$this->Language->_ARRAY['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" multiple data-placeholder="Share to" tabindex="-1" aria-hidden="true" id="users" name="users[]" data-select2-id="users">
                <option value="0">User1</option>
                <option value="1">User2</option>
              </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>Submit</button></div>
      </div>
    </div>
  </div>
  </div>
</form>