使用jQuery Validation验证select

时间:2017-10-21 14:16:19

标签: javascript jquery jquery-validate

我正在尝试向选择框添加验证,但我收到错误has no name assigned我不知道在指定的命名方面我错了...

我正在使用MaterialiseCSS框架,我怀疑其中的某些内容与jQuery Validation相冲突。

我的脚本版本。

 <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 <script type="text/javascript" src="modules/jquery.validate.min.js"></script>
<script type="text/javascript" src="modules/additional-methods.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/localization/messages_pt_BR.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.10.3/sweetalert2.all.min.js"></scrip

选择框。

  <form id="transporter" name="transporter" action="transporter/new" method="post" role="form">
    <div class="input-field col s12">
      <i class="material-icons prefix">more_vert</i>
      <select id="statusTransporter" name="statusTransporter">
        <option value="" disabled selected>Selecione uma situação de atividade para seu transportador</option>
        <option value="ativo" id="activeStatusTransporter">Ativo</option>
        <option value="inativo" id="inactiveStatusTransporter">Inativo</option>
        <option value="pendente" id="pendingStatusTransporter">Pendente</option>
      </select>
      <label>Situação do transportador:</label>
    </div>
  </form>

验证规则。

  jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
  });

  var transporterPublish = $("#transporter");

  transporterPublish.validate({
    lang: 'pt_BR',
    errorClass: 'error',
    errorElement: "div",
    errorPlacement: function (error, element) {
      var placement = $(element).data('error');
      if (placement) {
        $(placement).append(error)
      } else {
        error.insertAfter(element);
      }
    },

    rules: {
      statusTransporter: {
        required: true
      }
    }
  });

点击按钮后会启动的Ajax。

      $('#publish-transporter').click(function () {
        var payload = {
          statusTransporter: $('#statusTransporter').val()
        };

        if (transporterPublish.valid()) {
          $.ajax({
            url: "/transporter/sucess",
            type: "POST",
            contentType: "application/json",
            processData: false,
            data: JSON.stringify(payload),
            complete: function (data) {
              swal(
                'Good job!',
                'You clicked the button!',
                'success'
              )
            }
          });
        }
        return false
      });

感谢您的帮助!

0 个答案:

没有答案