语义形式验证 - 将任一字段验证为非空

semantic form validation - Validation for either one of the fields as non-empty

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

<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>

`

我会创建一个语义 UI 自定义验证函数,它接受您的目的参数。 这是 link: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);

});

这里有一个更优雅的解决方案,它遵循 Semantic UI 字段识别标准。
字段不仅可以通过 input[name="…"] CSS 选择器在 Oniisaki 接受的答案中提供,还可以通过 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.'
    }]
  }
});

如果您想包含 select 框,您可以像这样使用它:

$.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;
};