开发者

Validate Custom Input URL fields with jQuery & Regex

So basically I'm trying to validate URLs (http://www.x) - currently working - and on top of that, validate jsFiddle (input must start with "http://www.jsfiddle.net/") & stackoverflow URLs (input must start with "http://www.stackoverflow.com/")

Here is a working fiddle http://jsfiddle.net/eAnS9/

The validation is the bassistance validate plugin, which is documented here.

Any idea how to validate the fields correctly based on their beginning values?

UPDATE: It must work with/integrate开发者_开发技巧 with bassistance current validation, maybe as a custom url function in bassistance source code? (there is where the url regex is)


Use validator.addMethod() to create a custom rule. This one should do the trick:

//--- 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");
    }
);

Now connect it to a CSS class. :

jQuery.validator.addClassRules ( { domainChk: {domainChk: true} } );


The domainChk rule expects the required domain to be in the rel attribute of the input, like so:

<input class="field required url domainChk" rel="jsfiddle.com"      ...>
<input class="field required url domainChk" rel="stackoverflow.com" ...>


That's it!   See it all in action at jsFiddle.


could be better but

   var Reg = /https?:\/\/(w{3}\.)?(jsfiddle|stackoverflow)(.com\/)/

is what i used. http://jsfiddle.net/eAnS9/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜