使用validator.addMethod()
來創建自定義規則。這一個應該做的伎倆:
//--- Add a domain-check rule
jQuery.validator.addMethod ("domainChk", function (value, element, params) {
if (this.optional (element))
return true;
//--- Get the target domain, this will be in the rel attribute.
var targDomain = $(element).attr ("rel");
var regExp = new RegExp ("^https?:\/\/(www.)?" + targDomain + "\/", "i");
return regExp.test (value);
},
function errmess (params, element) {
return "This must be a valid URL for " + $(element).attr ("rel");
}
);
現在將其連接到一個CSS類。 :
jQuery.validator.addClassRules ({ domainChk: {domainChk: true} });
的domainChk
規則預計所需的站點是在輸入的相對屬性,就像這樣:
<input class="field required url domainChk" rel="jsfiddle.com" ...>
<input class="field required url domainChk" rel="stackoverflow.com" ...>
這就是它! See it all in action at jsFiddle.
完美答案。非常感謝Brock,今天我學到了很多:) – Maverick
不客氣;樂意效勞。 –