2012-08-30 33 views
0

我正在研究一些使用.js文件處理客戶端JavaScript的遺留代碼。在表格中,用戶可以通過點擊加號和減號按鈕來動態創建的字段:在Javascript中動態創建的表單字段上執行驗證

enter image description here

我用jQuery這樣做:

$(document).ready(function() 
{ 
    var html = "<div class='registration_box01' id='showme'> <div class='title'> <h4>Additional Guest<br /></h4> </div> <div class='content'> <div class='clr'></div> <div class='label01'>*First name:</div> <div class='field01'> <input name='add_fname[]' type='text' size='40' style='min-width:250px;' /> </div> <div class='clr'></div> <div class='label01'>*Last name:</div> <div class='field01'> <input name='add_lname[]' type='text' size='40' style='min-width:250px;' /> </div> <div class='clr'></div> <div class='label01'>*Email:</div> <div class='field01'> <input name='add_email[]' type='text' size='40' style='min-width:250px;'> </div> </div> </div>"; 
    $(function() { 
     $("#inc").click(function() { 
     var num = $(":text[name='qty']").val(function(i, v) { 
         return Number(v) + 1; 
        }).val(); 
     $(this).addClass ('c' + num); 
     var incrementVar = num; 
     $('.additional').append(html); 
     }); 

     $("#dec").click(function() {    
     $(":text[name='qty']").val(function(i, v) { 
     $("#showme").remove(); 
      if(Number(v) > 1){            
       return Number(v) - 1; 
      } 
      else{  
       return 1; 
      } 
     }); 
     }); 
    }); 
}); 

我的問題是如何驗證Javascript中的動態字段?我想我不會反對在jQuery中添加一個函數來檢查它們。我現在的功能驗證表單:

Pastebin

HTML:

<form action="register.php" method="post" onsubmit="return validateFrm(this);"> 

回答

0

我覺得自己像一個簡單的方法來做到這一點是給每個輸入某一類。因此,例如,「名字」文本框應具有類「fname-textbox」。在你的驗證函數中,你知道所有的「名字」文本框不應該是空的,也許應該至少有2個字符長(或其他)。所以你可以這樣做:

function validateFrm(form) { 
    var isValid = true; 
    var $form = $(form); 
    $form.find(".fname-textbox").each(function() { 
     var $this = $(this); 
     var $this_val = $this.val(); 
     if (isNaN($this_val) && $this_val.length > 1) { 
      $(this).removeClass("input-validation-error"); // won't fail if it doesn't have the class already 
      // Remove any other indications of error for this field (like a "*" next to it) 
     } else { 
      isValid = false; 
      $(this).addClass("input-validation-error"); // maybe input-validation-error has a red border and red text color? 
      // Maybe add another indication of error for this field (like a "*" next to it) 
     } 
    }); 
    // And continue the validation for your other fields 
    return isValid; 
}