2013-06-24 21 views
0

請參閱http://jsfiddle.net/gVVa8/7/jquery驗證器 - http | https | ftp | www

我想驗證http | https | ftp |萬維網。但似乎無法讓它驗證https網址。

任何人都可以幫忙嗎?

$(document).ready(function() { 
// Validates http | https | ftp 
// http://www.cnn.com | https://www.facebook.com | ftp://myurl.com | www.igs.org 

    $.validator.addMethod("cus_url", function (value, element) { 
     if (value.substr(0, 7) != 'http://') { 
      value = 'http://' + value;   
     } 

     if (value.substr(value.length - 1, 1) != '/') { 
      value = value + '/'; 
     } 

     return this.optional(element) || /^(https|http):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(value); 
    }, "Not valid url."); 

    $("#myform").validate({ 
     ignore: [], 
    }); 

}); 
+1

你的函數的第一個幾行會變成'的https :// example.com'轉換爲'http:// https:// example.com',這將不會通過您的驗證。 – Paulpro

回答

0

添加&& value.substr(0, 8) != 'https://'到你的代碼,如:

$.validator.addMethod("cus_url", function (value, element) { 
    if (value.substr(0, 7) != 'http://' && value.substr(0, 8) != 'https://') { 
     value = 'http://' + value;   
    } 

或使用正則表達式,如:if (!value.match(/^http(s?):\/\//)) 否則你https://www.facebook.com將成爲http://https://www.facebook.com

+0

謝謝最終代碼http://jsfiddle.net/gVVa8/8/ – Lacer

相關問題