2015-07-21 3 views
2

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

`

+0

Как вы думаете, что случилось с кодом? Я попытался запустить его, и он отлично работает для меня. По умолчанию значение «ssn» заполняется, поэтому отправка без ввода чего-либо будет корректно проверяться, потому что уже есть текст. См. Этот JSFiddle: https://jsfiddle.net/k749gm55/1/ –

ответ

2

Я хотел бы создать семантическую 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); 

}); 
+0

Это работает, спасибо Oniisaki – lucy

2

Вот немного более элегантное решение, которое следует 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.' 
    }] 
    } 
}); 
0

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

$.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; 
}; 
Смежные вопросы