2012-07-09 183 views
1

我已經設置了使用jQuery的HTML表單的驗證,我正在尋找一些關於電話號碼驗證的幫助,我一直在網上搜索,這裏是我想出來的,但它仍然不工作!我有電子郵件和名稱輸入驗證,但無法弄清楚如何正確實施電話號碼驗證,因爲我提交時仍然接受信件?我需要輸入只接受最多15個數字,如果需要,還可以在開始時接受+號?使用jQuery的電話號碼驗證

我使用的regEx是:/^[a-zA-Z0-9._-][email protected][a-a-A-Z0-9.-]+.[a-zA-Z]{2,4 } $ /和我知道這是不正確的,但我甚至不能讓這個工作?

任何關於如何解決這個問題的意見非常感謝!

$('#submit_second').click(function(){ 
    //remove classes 
    $('#second_step input').removeClass('error').removeClass('valid'); 

    var emailPattern = /^[a-zA-Z0-9._-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
var phonePattern = /^[0-9]{3}\-[0-9]{7}$/ ; 
    var fields = $('#second_step input[type=text]'); 
    var error = 0; 
    fields.each(function(){ 
     var value = $(this).val(); 
     if(value.length<1 || value==field_values[$(this).attr('id')] || ($(this).attr('id')=='email' && !emailPattern.test(value)) ) { 
      $(this).addClass('error'); 
      $(this).effect("shake", { times:3 }, 50); 

      error++; 
     } else { 
      $(this).addClass('valid'); 
     } 
    if(value.length<1 || value==field_values[$(this).attr('id')] || ($(this).attr('id')=='phone' && !phonePattern.test(value)) ) { 
      $(this).addClass('error'); 
      $(this).effect("shake", { times:3 }, 50); 

      error++; 
     } else { 
      $(this).addClass('valid'); 
     } 


}); 

回答

2

這應做到:

/^\+?[0-9]{0,15}$/ 

這件事匹配15個號碼,可選前綴+

+0

嗨感謝您的!林不知道它只是regEx多數民衆贊成不起作用,我認爲我的代碼也是錯誤的?驗證電話號碼的代碼是否有誤?我沒有收到任何錯誤警告,但是當我將它提交給服務器時,它仍然接受字母和數字,但沒有給我警告? – DannyW86 2012-07-09 12:31:21

+0

我的代碼實際上工作確定我只是有一個命名錯誤,我的提交按鈕!謝謝 :) – DannyW86 2012-07-09 13:31:04