仅当 select 具有特定值时才需要填写字段

make a field required only if a select has a specific value

我有这个表格:

<form id="new_field" class="form-horizontal contact-form">
    <div class="form-group" class="colored-text">
        <label for="tipo_field" class="colored-text">Tipologia di campo: </label>
        <select class="form-control" id="tipo_field" name="tipo_field">
            <option value="">Scegli una tipologia di campo</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
    </div>
    <div class="form-group" id="alternatives_area" style="display:none;">
        <label class="colored-text">Alternative: </label>
        <textarea class="form-control" rows="3" name="alternatives" id="alternatives" style="display: none"></textarea>
    </div>
    <div class="form-group col-md-12">
        <button type="button" class="btn btn-success" id="field_submit"><i class="fa fa-check"></i> Crea</button>
        <button type="button" class="btn btn-secondary" id="undo_new_field"><i class="fa fa-undo"></i> Esci</button>
    </div>
</form>

我想对其使用验证,它适用于表单中的其他字段(从上面的代码中排除,因为它们不相关)。我未能实现的是制定一条规则,使 textarea #alternatives 成为必需,但仅当 #tipo_field select 值为 2 或 3 时才需要。

据我所知,我必须将 depends 用作 explained in the documentation,但我无法准确地指出如何应用它来满足我的要求。

我目前的js代码是:

$('#new_field').validate({
    rules: {
      nome_field: {
        required: true,
      },
      desc_field: {
        required: true,
        
      },
      tipo_field: {
        required: true
      },
    },
    messages: {
      nome_field: "Il nome del campo è richiesto",
      desc_field: "La label del campo è richiesta",
      tipo_field: "Per favore scegli una tipologia per questo campo"
    },
    errorElement: 'span',
    errorPlacement: function (error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function (element, errorClass, validClass) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function (element, errorClass, validClass) {
      $(element).removeClass('is-invalid');
    },
    submitHandler: function(form) {
        form.submit();
    }
  });

您说得对,您可以使用 depends 来满足您的要求。只需向 required 提供一个包含 depends 属性 的对象,以及一个 returns 布尔值的函数,以确定是否需要 #alternatives 字段。

此外,要在单击 Crea 按钮时触发验证逻辑,它需要是 type="submit" 元素,而不是 type="button"。试试这个:

$('#new_field').validate({
  rules: {
    nome_field: {
      required: true
    },
    desc_field: {
      required: true
    },
    tipo_field: {
      required: true
    },
    alternatives: {
      required: {
        depends: () => parseInt($('#tipo_field').val(), 10) > 1
      }
    }
  },
  messages: {
    nome_field: "Il nome del campo è richiesto",
    desc_field: "La label del campo è richiesta",
    tipo_field: "Per favore scegli una tipologia per questo campo"
  },
  errorElement: 'span',
  errorPlacement: function(error, element) {
    error.addClass('invalid-feedback');
    element.closest('.form-group').append(error);
  },
  highlight: function(element, errorClass, validClass) {
    $(element).addClass('is-invalid');
  },
  unhighlight: function(element, errorClass, validClass) {
    $(element).removeClass('is-invalid');
  },
  submitHandler: function(form) {
    console.log('valid');
    //form.submit();
  }
});
<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.2/jquery.validate.min.js" integrity="sha512-UdIMMlVx0HEynClOIFSyOrPggomfhBKJE28LKl8yR3ghkgugPnG6iLfRfHwushZl1MOPSY6TsuBDGPK2X4zYKg==" crossorigin="anonymous"></script>
<form id="new_field" class="form-horizontal contact-form">
  <div class="form-group" class="colored-text">
    <label for="tipo_field" class="colored-text">Tipologia di campo: </label>
    <select class="form-control" id="tipo_field" name="tipo_field">
      <option value="">Scegli una tipologia di campo</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
  </div>
  <div class="form-group" id="alternatives_area">
    <label class="colored-text">Alternative: </label>
    <textarea class="form-control" rows="3" name="alternatives" id="alternatives"></textarea>
  </div>
  <div class="form-group col-md-12">
    <button type="submit" class="btn btn-success" id="field_submit"><i class="fa fa-check"></i> Crea</button>
    <button type="button" class="btn btn-secondary" id="undo_new_field"><i class="fa fa-undo"></i> Esci</button>
  </div>
</form>

请注意,我在示例中使所有表单控件都可见,因为切换它们的逻辑未包含在原始问题中。

根据文档,您可以这样写:

alternatives: {
  required: {
    depends: () => parseInt($('#tipo_field').val(), 10) == 2 || parseInt($('#tipo_field').val(), 10) == 3
  }
}