【问题标题】:How to check that a form has AT LEAST one field filled in如何检查表格是否至少填写了一个字段
【发布时间】:2012-08-18 02:58:14
【问题描述】:

我正处于构建网站的最后阶段,还有一个关键任务:设置一些表单验证,阻止用户提交空白搜索。

我知道以下帖子,但发现不清楚如何使其工作以及如何将其用于下拉菜单 (jQuery Validate - require at least one field in a group to be filled)

任何关于我如何做到这一点的想法,或任何可能有帮助的指南指针,将不胜感激?

【问题讨论】:

  • 另外,请确保您在服务器端进行验证。
  • 可能是if($('#your-form input,#your-form select').filter(function (el) {return $(el).val() != '';}).length > 0) {/* validation passed */} 之类的?

标签: javascript jquery forms


【解决方案1】:
//select all text inputs in form and filter them based on...
var isFilled = $('input[type="text"]', 'form').filter(function() {
    return $.trim(this.value).length;  //text inputs have a value
}).length;                             //get the selector length

//if selector contains at least one filled in text input, submit form
if (isFilled) {..submit form..} 

【讨论】:

    【解决方案2】:
    var filled = $('.property-list input[type="text"]').filter(function() {
        var v = $(this).val();
        // sanitize it first
        v = v.replace(/[\s]{2,}/g,' ').replace(/^\s*(.*?)\s*$/,'$1');
        $(this).val(v);
        // if you want it to contain min.
        // 3 consecutive alphanumeric chars, for example...
        return /[a-z0-9]{3,}/i.test(v);
    }).get();
    if (filled.length) {
        // do whatever with the result
        alert('all okay');
    } else {
        $('.property-list input[type="text"]').focus().blur();
        // this is for the placeholders to refresh, at least in Safari...
        $('.property-list input[type="text"][value!=""]:first').focus();
        var msg = 'plase fill at least one field with min. 3 ';
        msg += 'consecutive alphanumeric characters';
        alert(msg);
    }
    

    【讨论】:

      【解决方案3】:

      这是一个适用于所有表单字段类型的函数:textselectradiocheckboxtextareafile 和 HTML5 输入类型,如 email。这个函数的唯一假设是所有select 元素都有一个optionvalue=""

      /**
       * 1) gather all checkboxes and radio buttons
       * 2) gather all inputs that are not checkboxes or radios, and are not buttons (submit/button/reset)
       * 3) get only those checkboxes and radio buttons that are checked
       * 4) get only those field elements that have a value (spaces get trimmed)
       * 5) if the length of both resulting collections is zero, nothing has been filled out
       */
      function checkFields(form) {
          var checks_radios = form.find(':checkbox, :radio'),
              inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]'),
              checked = checks_radios.filter(':checked'),
              filled = inputs.filter(function(){
                  return $.trim($(this).val()).length > 0;
              });
      
          if(checked.length + filled.length === 0) {
              return false;
          }
      
          return true;
      }
      
      $(function(){
          $('#myForm').on('submit',function(){
              var oneFilled = checkFields($(this));
              // oneFilled === true if at least one field has a value
          });
      });​
      

      这是一个演示:

      --- jsFiddle DEMO ---

      【讨论】:

      • 嗨@jackwanders,这真的很有帮助,谢谢。我现在已经成功地检查了表单的脚本。这似乎是一个简单的问题,但是我如何告诉脚本至少在一个字段被填写后允许提交按钮来汇总搜索?
      • 我现在通过阅读this 帖子让提交按钮再次工作。如果至少填写了一个字段,我只是添加了一行$(this).unbind('submit').submit()。唯一的问题是提交按钮现在似乎需要单击两次。一个用于向按钮添加默认功能,另一个用于实际提交表单。有什么想法吗?
      • 无需解绑并重新提交表单。我假设您在问表单如何转到表单的action 属性中指示的页面?如果表单的submit 处理程序返回false,则表单将不会继续提交。如果返回 true,则执行表单的操作。
      【解决方案4】:

      我不是专家,但这对我有用。我有一个选择字段和一个用于捐赠的输入字段。如果金额不在选择选项上,则用户可以将金额添加到输入字段中。所以至少要提交一份。

          function validateForm() {  
      if (  myform.mySelectfield.value == "" 
          && myform.myInputfield2.value == "" 
          ) {
      alert( "Please enter at least field" );
           return false;    
           }   
           } 
      //--> 
      

      当然,输入字段必须是数字,所以我添加了:

       function validateForm2() {
      

      var x=document.forms["myform"]["myInputfield2"].value;

      if (/[^0-9]+$/.test(x))
          {
          alert("Please enter a numerical amount without a decimal point");
          myform.myInputfield2.focus();
          return false;
        } 
      

      }

      数值校验称为onkeyup:

      onkeyup="validateForm2()"
      

      我不得不创建第二个函数 validateForm2(),因为数字检查不适用于第一个函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        • 2023-04-10
        • 2013-12-29
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多