2012-10-05 60 views
0

我無法讓自定義網址驗證規則發揮作用。如何在不使用http的情況下進行url驗證(或在驗證通過後添加它)?

我添加新的規則:

jQuery.validator.addMethod("complete_url", function(val, elem) { 
// if no url, don't do anything 
    return /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w][email protected])?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w][email protected])[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/.test(val); 
    }); 
... 
$("#new_website").validate({ 
    rules: { 
      url: "complete_url", 
     'website[url]': { 
      url: true, 
      required: true} 
      } 
     }); 

但它返回我

invalid URL 

我檢查正則表達式在這裏 - http://www.rubular.com/。它正在工作,但未能通過我的自定義驗證器。

我在做什麼錯了?

回答

3
jQuery.validator.addMethod("checkurl", function(value, element) { 
// now check if valid url 
return /^(www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/.test(value); 
}, "Please enter a valid URL." 
); 

// connect it to a css class 
    jQuery.validator.addClassRules({ 
checkurl : { checkurl : true }  
}); 
    ... 
    'website[url]': { 
      checkurl: true 
    } 
+0

這是什麼?這是一個有效的答案嗎?我正在尋找相同問題的解決方案。 – stephenmurdoch

+0

@marflar,它爲我工作。試試看,並告訴我是否可以。 – skrypalyk

3

我用這個和它工作得很好

jQuery.validator.addMethod("url2", function(value, element, param) { 
return this.optional(element) || /^(www\.)(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); 
}, jQuery.validator.messages.url); 
4

,請不要使用正則表達式這一點。甚至不要使用jQuery驗證程序使用的相同正則表達式,它可能會在將來更改,並且您將無法利用更新。這是這樣做的:

$.validator.addMethod('validUrl', function(value, element) { 
     var url = $.validator.methods.url.bind(this); 
     return url(value, element) || url('http://' + value, element); 
    }, 'Please enter a valid URL'); 
+0

這是實現理想結果的更好方法,在盒子外面思考的道具! – Harry

相關問題