JQuery валидатор проверяет ложно - одно из двух полей, обязательных для заполнения - PullRequest
0 голосов
/ 30 сентября 2019

У меня есть форма, в которой я хочу указать номер телефона посетителя или адрес электронной почты. Я хочу требовать этого, хотя форма является формой запроса информации, и я хочу убедиться, что у меня есть хотя бы один канал обратной связи - предоставляя пользователю выбор, какой из них использовать (или, возможно, оба) .

Я поражен здесь некоторое время и не мог найти соответствующую информацию в других, очень похожих вопросах - как-то все это не подходило. Пожалуйста, прости меня, поэтому дублирующий вопрос;Я просто не вижу, где я ошибаюсь. Вот моя почти полная форма (только зачеркнуто то, что я нашел хорошим, а также ненужным для вопроса) :

  <div class="propertydetailrequest form-group">
    <input type="text" name="cntnt01fbrp__31" value="" class="form-control" required="" placeholder="Your Name *" id="fbrp__31" />
  </div>
  <div>
    <input type="email" name="cntnt01fbrp__58[]" value="" class="form-control require-one" placeholder="Your Email" id="fbrp__58_1" />
  </div>
  <div>
    <input type="text" name="cntnt01fbrp__33" value="" class="form-control require-one" placeholder="Your Telephone" id="fbrp__33" />
  </div>
  <div class="required">
    <input type="checkbox" class="form-control" name="cntnt01fbrp__56" value="t" required="required" id="fbrp__56" />
    <label for="fbrp__56">I read and have accepted the <a href="gdpr.html">privacy policy</a> <span class="red">*</span></label>
  </div>
  <div>
    <script>
// adding script here within the form instead of in a global script file
// using vanilla JS to enable jQuery after it has been loaded before </body>
  document.addEventListener('DOMContentLoaded', function () {
  $("#cntnt01fbrp_submit").addClass('disabled');
  $("#cntnt01fbrp_submit").prop('disabled', true);

  $.getScript("http://example.com/assets/js/validate.min.js", function () {
    $( "#cntnt01moduleform_1" ).validate({
      errorPlacement: function(error,element) {
        return true; // just hiding that error message
      },
      rules: {
        fbrp__58_1: {
          require_from_group: [1, ".require-one"],
          email: true // does validate email addresses and empty is fine too
        },
        fbrp__33: {
          require_from_group: [1, ".require-one"]
        }
      }
    }); // eof validate
  });  //eof getscript

// trying to make sending the form without validation impossible
  $('#cntnt01moduleform_1 input').on('keyup blur', function () {
    if ($('#cntnt01moduleform_1').valid()) {
      console.log('validated onBlur'); // make sure the plugin validates and not the browser
      $('input#cntnt01fbrp_submit').removeClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', false);
    } else {
      $('input#cntnt01fbrp_submit').addClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', true);
    }
  });
  $('#fbrp__56').change(function() {
    if ($('#cntnt01moduleform_1').valid()) {
      console.log('validated onClick'); // make sure the plugin validates and not the browser
      $('input#cntnt01fbrp_submit').removeClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', false);
    } else {
      $('input#cntnt01fbrp_submit').addClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', true);
    }
  });

});  // eof dom load
</script> 
  </div>
  <div class="submit text-right">
    <input class="btn btn-success" name="cntnt01fbrp_submit" id="cntnt01fbrp_submit" value="Senden" type="submit"  />
  </div>
</form>

Однако форма действительна только после того, как она дала только имя (требуется атрибутом HTML) и проверка флажка GDPR на (это также требуется HTML) . Очевидно, плагин валидатора действительно проверяет форму - хотя я спрашиваю его в опциях, чтобы сделать один из них обязательным. Журналы консоли должны быть стерты позже - я просто пытаюсь выяснить, какое событие происходит при этом.

1 Ответ

0 голосов
/ 30 сентября 2019

Вам необходимо включить все необходимые плагины jquery. Поэтому вы также должны включить библиотеку дополнительных методов

Кроме того, насколько я знаю, имена правил должны ссылаться на имена (а не идентификатор) входных данных, поэтому не используйтеfbrp__58_1 и fbrp__33, а точнее cntnt01fbrp__58 и cntnt01fbrp__33 соответственно

Поэтому:

   <form id="cntnt01moduleform_1">
        <div class="propertydetailrequest form-group">
            <input type="text" name="cntnt01fbrp__31" value="" class="form-control" required="" placeholder="Your Name *" id="fbrp__31" />
        </div>
        <div>
            <input type="email" name="cntnt01fbrp__58" value="" class="form-control require-one" placeholder="Your Email" id="fbrp__58_1" />
        </div>
        <div>
          <input type="text" name="cntnt01fbrp__33" value="" class="form-control require-one" placeholder="Your Telephone" id="fbrp__33" />
        </div>com
        <div class="required">
          <input type="checkbox" class="form-control" name="cntnt01fbrp__56" value="t" required="required" id="fbrp__56" />
          <label for="fbrp__56">I read and have accepted the <a href="gdpr.html">privacy policy</a> <span class="red">*</span></label>
        </div>

        <div>
        <script>
            // adding script here within the form instead of in a global script file
            // using vanilla JS to enable jQuery after it has been loaded before </body>
        document.addEventListener('DOMContentLoaded', function () {

          $("#cntnt01fbrp_submit").addClass('disabled');
          $("#cntnt01fbrp_submit").prop('disabled', true);


            $( "#cntnt01moduleform_1" ).validate({
              errorPlacement: function(error,element) {
                return true; // just hiding that error message
              },
              rules: {
                cntnt01fbrp__58: {
                  require_from_group: [1, ".require-one"],
                  minlength: 2 //I just added this. You can remove it if you want to
                  //email: true // does validate email addresses and empty is fine too
                },
                cntnt01fbrp__33: {
                  require_from_group: [1, ".require-one"],
                  minlength: 2 //I just added this. You can remove it if you want tp
                }
              } 
            }); // eof validate



        // trying to make sending the form without validation impossible
          $('#cntnt01moduleform_1 input').on('keyup blur', function () {

            if ($('#cntnt01moduleform_1').valid()) {

              console.log('validated onBlur'); // make sure the plugin validates and not the browser
              $('input#cntnt01fbrp_submit').removeClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', false);
            } else {
                console.log('validation failed')
              $('input#cntnt01fbrp_submit').addClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', true);
            }
          });
          $('#fbrp__56').change(function() {
            if ($('#cntnt01moduleform_1').valid()) {
              console.log('validated onClick'); // make sure the plugin validates and not the browser
              $('input#cntnt01fbrp_submit').removeClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', false);
            } else {
              $('input#cntnt01fbrp_submit').addClass('disabled'); $("#cntnt01fbrp_submit").prop('disabled', true);
            }
          });

        });  // eof dom load
    </script> 
  </div>
  <div class="submit text-right">
    <input class="btn btn-success" name="cntnt01fbrp_submit" id="cntnt01fbrp_submit" value="Senden" type="submit"  />
  </div>
</form>

Добавьте это в свой файл как раз перед </body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js" integrity="sha256-xLhce0FUawd11QSwrvXSwST0oHhOolNoH9cUXAcsIAg=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js" integrity="sha256-vb+6VObiUIaoRuSusdLRWtXs/ewuz62LgVXg2f1ZXGo=" crossorigin="anonymous"></script>  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...