验证复制的|克隆的输入字段是否具有相同的信息

时间:2016-08-15 12:54:01

标签: javascript jquery html forms validation

让我说我有以下表格信息:

<form name="form_name" id="form_name" method="post">
    <div class="form_div_0">
        <label>Firstname</label>
        <input type="text" name="input_firstname[0]" id="input_firstname[0]" />
        <label>Lastname</label>
        <input type="text" name="input_lastname[0]" id="input_lastname[0]" />
    </div>
    <button id="copy_form">Copy form</button>
    <input type="submit" value="Submit" />
</form>

复制表单按钮的功能是创建表单输入的副本,例如,如果我单击两次按钮,表单将更改为:

<form name="form_name" id="form_name" method="post">
    <div class="form_div_0">
        <label>Firstname</label>
        <input type="text" name="input_firstname[0]" id="input_firstname[0]" />
        <label>Lastname</label>
        <input type="text" name="input_lastname[0]" id="input_lastname[0]" />
    </div>
    <div class="form_div_1">
        <label>Firstname</label>
        <input type="text" name="input_firstname[1]" id="input_firstname[1]" />
        <label>Lastname</label>
        <input type="text" name="input_lastname[1]" id="input_lastname[1]" />
    </div>
    <div class="form_div_2">
        <label>Firstname</label>
        <input type="text" name="input_firstname[2]" id="input_firstname[2]" />
        <label>Lastname</label>
        <input type="text" name="input_lastname[2]" id="input_lastname[2]" />
    </div>
    <button id="copy_form">Copy form</button>
    <input type="submit" value="Submit" />
</form>

您可能会注意到我只复制div class="form_div_0"内的输入。

有了这些信息,我需要找到一种方法来验证遵循此规则的每个输入上输入的值:firstname和lastname在任何时候都不能相等。

例如:如果我输入firstname =&#34; John&#34;姓氏=&#34; Doe的&#34;对于form_div_0包裹的输入,我不能在form_div_1form_div_2form_div_n中包含相同的值。

我应该补充一点,这里的输入只是表格的一个例子(它是一个巨大的形式,有很多输入和不同的类型,如复选框,选项,选择和textarea)

另外,你可以看到我可以创建N个副本(它将有20个限制)。

您知道进行此验证的方法吗?有没有解决方法或库?有什么建议吗?

一旦输入失去焦点(意味着用户停止在其上键入)或提交时就可以进行验证但是我更喜欢第一种选择,否则用户可能会输入所有数据而我希望它们停止任何这个问题都会发生。

2 个答案:

答案 0 :(得分:1)

请查看以下解决方案,是否适用于您

&#13;
&#13;
$(function(){
   $("#copy_form").on('click', function(e) {
      e.preventDefault();
   		var currentLength = $("[class^='form_div']").length;
      $(".error").html("");
      if (currentLength >  20 ) {
      	$(".error").html("Reaches maximum form limit");
        return ;
      }
      var previousElement =  currentLength-1;
      
      var $formDiv = $(".form_div_"+ previousElement);
      var $firstNameLabel = $("<label/>").html("FirstName");
      var $lastNameLabel = $("<label/>").html("LastName");
      var $firstName = $("<input/>").attr("type","text").attr("name","input_firstname_"+currentLength).attr("id","input_firstname_"+currentLength);
      var $lastName = $("<input/>").attr("type","text").attr("name","input_lastname_"+currentLength).attr("id","input_lastname_"+currentLength);
    var $nextDiv = $("<div/>").attr("class","form_div_"+ currentLength).append($firstNameLabel).append($firstName).append($lastNameLabel).append($lastName);
    $formDiv.after($nextDiv);
    
   });
   
   $("#form_name").submit(function(e) {
      e.preventDefault();
      var currentLength = $("[class^='form_div']").length;
      var firstNameArray  = [];
      var lastNameArray  = [];
      for( var i = 0; i < currentLength ; i++ ) {
          var $firstName = $("#input_firstname_"+i);
           var $lastName = $("#input_lastname_"+i);
           if ($firstName.val() != "" && $lastName.val() != "" && $firstName.val() === $lastName.val() ) {
               $(".error").html("First Name and Last Name are same in form" + i);
           }
           if (currentLength > 1 ) {
              if ($firstName.val() != "") {
           		 if ($.inArray($firstName.val(),firstNameArray ) == -1) {
           			firstNameArray.push($firstName.val());
               }     
               else {      
                  $(".error").append("Duplicate firstName in form" + i);
               }
              } 
							
              if ($lastName.val() != "") {
               if ($.inArray($lastName.val(),lastNameArray ) == -1) {           			                                                   lastNameArray.push($lastName.val());
               }
               else {      
                  $(".error").append("Duplicate lastName in form" + i);   
               }
             }
           }  
              
              
      }
      
      
   });
   
});
&#13;
.error {
  color: red;
  font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form_name" id="form_name" method="post">

<span class="error"></span>
    <div class="form_div_0">
        <label>Firstname</label>
        <input type="text" name="input_firstname[0]" id="input_firstname_0" />
        <label>Lastname</label>
        <input type="text" name="input_lastname[0]" id="input_lastname_0" />
    </div>
    <button id="copy_form">Copy form</button>
    <input type="submit" value="Submit" />
 </form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我可以通过使用纯JS来实现如下,而不使用任何库。我使用的是ES6工具,但如果需要的话,用ES5等价物替换它们相当简单。

一旦场失去焦点,它会立即进行重复检查。没有为提交按钮指定任何功能,因为它仅用于提交表单。

return type fn(...)
function checkOnBlur(e){
  var enteredValues = inEls.map(inel => inel.value);
       enteredValue = e.currentTarget.value;
  if (enteredValues.filter(ev => ev === enteredValue).length > 1 && enteredValue !== ""){
    e.currentTarget.value = "";
    e.currentTarget.setAttribute("placeholder", "Duplicate..! Enter Again.");
    e.currentTarget.focus();
  } else e.currentTarget.removeAttribute("placeholder");
}

function cloneFormDiv(e){
  var dl = [...myForm.querySelectorAll("[class*='form_div']")],
  newDiv = dl[0].cloneNode(true),
newInEls = newDiv.querySelectorAll("input");

  e.preventDefault();
  newDiv.className = "form_div_" + dl.length;
  [newInEls[0].id, newInEls[0].name, newInEls[0].value] = ["input_firstname_" + dl.length, "input_firstname_" + dl.length,""];
  [newInEls[1].id, newInEls[1].name, newInEls[1].value] = ["input_lastname_" + dl.length, "input_lastname_" + dl.length,""];
  for(var inel of newInEls) {inel.addEventListener("blur", checkOnBlur);
                             inEls.push(inel)}
  myForm.appendChild(dl.concat(newDiv)
                       .reduce((frag,d) => (frag.appendChild(d),frag), document.createDocumentFragment()));
}

var myForm = document.getElementById("form_name"),
     inEls = [...myForm.querySelectorAll("div input")],
copyButton = myForm.querySelector("#copy_form");
for (var inel of inEls) inel.addEventListener("blur", checkOnBlur);
copyButton.addEventListener("click", cloneFormDiv);