проверка семантической формы - проверка для любого из полей как непустого

У меня есть форма, в которой у меня 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>

`


person Bobby    schedule 21.07.2015    source источник
comment
Как вы думаете, что не так с вашим кодом? Я попробовал запустить его, и он у меня отлично работает. По умолчанию значение ssn заполняется, поэтому отправка без ввода текста будет проверяться правильно, потому что текст уже есть. См. Этот JSFiddle: jsfiddle.net/k749gm55/1   -  person Franz Payer    schedule 22.07.2015


Ответы (3)


Я бы создал специальную функцию проверки семантического пользовательского интерфейса, которая принимает параметры для ваших целей. Вот ссылка: 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);

});
person MTran    schedule 25.07.2015

Вот немного более элегантное решение, соответствующее стандарту идентификации полей Semantic UI.
Поле можно было идентифицировать не только с помощью input[name="…"] селектора CSS, предлагаемого в принятом ответе Oniisaki, но также по идентификатору элемента DOM или 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.'
    }]
  }
});
person Nik Sumeiko    schedule 28.11.2015
comment
Очень элегантно, спасибо! - person WhatsInAName; 20.04.2021

Если вы хотите включить поле выбора, вы можете использовать его так:

$.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;
};
person osmanraifgunes    schedule 18.05.2016