2012-02-13 170 views
1

我已經在窗體上設置jQuery驗證,驗證當前測試的電話號碼字段不是空的,是一個數字,但我希望它能夠處理放置移動/區號之後的空格。Jquery表單驗證 - 電話號碼

任何人都可以建議我需要做什麼來允許這個嗎?

這是我當前的代碼 -

if((phone.length == 0) || (names == 'Please Enter Your Contact Number (no space)')){ 
     var error = true; 
     $('.error').fadeIn(500); 
     $('.pStar').fadeIn(500); 

    }else{ 
     var value = $('#phone').val().replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
     var intRegex = /^\d+$/; 
     if(!intRegex.test(value)) { 
      var error = true; 
      $('.error').fadeIn(500); 
      $('.pStar').fadeIn(500); 

     } else{ 
     $('.pStar').fadeOut(500); 
     } 
    } 
+0

您能否提供一些有效/無效的輸入? – hsz 2012-02-13 15:21:05

回答

5

我會強烈建議使用jQuery validate,而不是重新發明輪子

一個快速谷歌搜索與JQuery驗證英國的電話號碼原來這件事

filters

看起來像這樣

jQuery.validator.addMethod('phoneUK', function(phone_number, element) { 
    return this.optional(element) || phone_number.length > 9 && 
    phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/); 
    }, 'Please specify a valid phone number' 
); 
+0

歡迎您的幫助 – Dancer 2012-02-13 16:02:09

+0

歡迎@保羅很高興我能幫到 – mcgrailm 2012-02-13 16:12:19

3

使用此正則表達式來驗證電話號碼。

var pattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; 
if(!$('#phone').val().test(elementValue)){ 
    //Invalid number 
} 

此正則表達式將可選地接受開始(或區域代碼結束)和後區碼後前3位數字將可選地接受-

+0

當然,這隻適用於北美的數字。 – chris 2012-02-13 15:22:45

+0

對不起,我應該說 - 這需要爲英國號碼工作.. – Dancer 2012-02-13 15:25:33

+0

是的,它主要是爲美國的號碼,但將驗證其他電話號碼格式也很少或根本沒有變化,因爲'()'和' - '是可選的。 – ShankarSangoli 2012-02-13 15:27:06