2013-03-12 46 views
0

(我不使用jQuery驗證)檢查驗證與ID和指定自定義錯誤

我試圖返回自定義錯誤如果字段不正確或空。例如,如果#id_first_name字段爲空。追加的字符串,「名」,以p#error導致:

Please fill in your first name 

我做了一個fiddle here顯示我的意思。因此,在必填字段列表中...我如何能夠抓住/檢查每個人所需的ID並分配相應的錯誤?

非常感謝您的幫助!

回答

1

你撥弄應該是最基本的可能,刪除所有其他信息,但你可以嘗試這樣的事情,

$('form').on('submit',function(){ 
    $('input').each(function(){ 
     $this = $(this); 
     if($this.val() == 'null') 
     { 
     $('p#error').append('Please enter your ' + $this.attr('placeholder')); 
     } 
    } 
}); 
+0

工作! '$ this.attr('placeholder')'是一個好主意,尤其是在循環播放時。謝謝! – Modelesq 2013-03-13 17:46:13

+0

沒問題,我很高興它有幫助。 – dev 2013-03-13 17:48:49

0

你可以做類似下面

$('form input').on('blur', function() { 
    var id = $(this).attr('id'); 
    var val = $(this).val(); 
    if(id == 'myInput') { 
      if(!val.length) { 
       $('#error').append('Please enter a value into the input'); 
      } 
    } 
}); 

這是做表單驗證一個簡單的方法,只是調整的例子您的需求。

編輯

如果你想讓它在你的榜樣工作,這將是更好的與的error id的div和追加p標籤與相應的誤差值。

編碼愉快:)