【问题标题】:semantic form validation - Validation for either one of the fields as non-empty语义形式验证 - 验证任一字段为非空
【发布时间】:2015-07-21 07:44:21
【问题描述】:

我有一个表单,其中有 2 个字段,ssn 和电话。我希望用户输入该领域的任何人。我正在使用语义验证,这是我的代码,你能告诉我如何使用语义验证表单吗?

<form class="ui error form basic segment" role="form" method="POST" action="{{ url('/username/email') }}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="_method" value="patch">
    <div class="ui info message">
        Please enter either SSN or phone to email you the username.
    </div>

    <div class="field">
        <label for="ssn">SSN</label>
        <div class="ui icon input">
            <input type="text" class="form-control" name="ssn" value="{{ old('ssn') }}">  
        </div>
    </div>
    <div class="field">
        <label for="phone">Phone</label>
        <div class="ui icon input">
            <input type="text" class="form-control" name="phone" value="{{ old('phone') }}">  
        </div>
    </div>

    <input type="submit" value="Email Username" class="ui primary button"> 

</form>
<script type="text/javascript">
      $('.ui.form')
      .form({
        inline : true,
        on: 'blur',
        fields: {
          username: {
            identifier : 'ssn',
            rules: [
              {
                type   : 'empty',
                prompt : 'Please enter a SSN'
              }
            ]
          },
        }
      })
    ;
</script>

`

【问题讨论】:

  • 您认为您的代码有什么问题?我尝试运行它,它对我来说很好。默认情况下,“ssn”的值是填充的,因此不输入任何内容的提交将正确验证,因为已经有文本。请参阅此 JSFiddle:jsfiddle.net/k749gm55/1

标签: semantic-ui


【解决方案1】:

我将创建一个语义 UI 自定义验证函数,该函数根据您的目的接受参数。 这是链接:http://jsfiddle.net/owcfuhtq/

代码:

$(document).ready(function(){
    // function to check if at least one text is not empty for a collection of elements
    // text is the value of the input device
    // csv is the argument as string. It's the string inside "[" and "]"
    $.fn.form.settings.rules.isAllEmpty = function(text,csv){
        //If the text of the field itself isn't empty, then it is valid
        if (text)
            return true;
        var array = csv.split(','); // you're separating the string by commas
        var isValid = false; // return value

        $.each(array,function(index,elem){
            // for each item in array, get an input element with the specified name, and check if it has any values
            var element = $("input[name='"+elem+"']");
            //If element is found, and it's value is not empty, then it is valid
            if (element && element.val())
                isValid = true;
        });
        return isValid; 
    };

    var formValidationRules =
    {
        ssn: {
          identifier: 'ssn',
          rules: [{
            type: "isAllEmpty[phone]",
            //If you got additional fields to compare, append it inside the [] with a "," separator
            //E.g. isAllEmpty[field1, field2]
            prompt: 'An error occurred'
          }]
        }
    }

    $('.ui.form').form(formValidationRules);

});

【讨论】:

    【解决方案2】:

    这里有一个更优雅的解决方案,它遵循Semantic UI 字段识别标准。
    字段不仅可以通过Oniisaki 接受的答案中提供的input[name="…"] CSS 选择器来识别,还可以通过DOM 元素id 或data-validation 属性来识别:

    /**
     * Checks whether current field value or at least one of additionally 
     *   given fields values is not empty, neither blank string.
     * @param {string} value Current field value.
     * @param {string} fieldIdentifiers Comma separated field identifiers.
     * @return {boolean}
     */
    $.fn.form.settings.rules.allEmpty = function(value, fieldIdentifiers) {
      var $form = $(this);
    
      return !!value || fieldIdentifiers.split(',').some(function(fieldIdentifier) {
        return $form.find('#' + fieldIdentifier).val() ||
            $form.find('[name="' + fieldIdentifier +'"]').val() ||
            $form.find('[data-validate="'+ fieldIdentifier +'"]').val();
    
      });
    };
    
    
    // Using newly created custom validation rule.
    // Notice how multiple fields are defined, if required.
    $('.ui.form').form({
      ssn: {
        identifier: 'ssn',
        rules: [{
    
          // Multiple field identifiers could be defined, 
          // like `allEmpty[phone,email,skype]`.
          type: 'allEmpty[phone]',
          prompt: 'SSN or Phone (at least one field) must be filled.'
        }]
      }
    });
    

    【讨论】:

      【解决方案3】:

      如果你想包含选择框,你可以像这样使用它:

      $.fn.form.settings.rules.isAllEmpty = function (text, csv) {
          if (text) {
              return true;
          }
          var array = csv.split(',');
          var isValid = false;
      
          $.each(array, function (index, elem) {
              var element = $("input[name='" + elem + "']");
      
              if (element.length == 0) {
                  element = $("select[name='" + elem + "']")
              }
      
              if (element && element.val()) {
                  isValid = true;
              }
          });
          return isValid;
      };
      

      【讨论】:

        猜你喜欢
        • 2014-06-17
        • 1970-01-01
        • 2020-10-23
        • 1970-01-01
        • 2019-06-11
        • 2015-02-05
        • 2017-01-22
        • 2011-07-23
        • 2012-02-20
        相关资源
        最近更新 更多