Javascript验证网址

时间:2014-05-07 10:06:14

标签: javascript jquery

我使用以下代码验证客户端的URL。我的问题是,是否有更好的方法来做同样的事情。我的问题不是我正在使用的正则表达式(只是整体写作方式)

this.validators.myUrl = function(value) {
    if (!_.isUndefined(value) && !_.isNull(value)) {

    if ($.trim(value).length == 0) {
        return {
            isValid: true
        } 
    }   else {

        return /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test($.trim(value)) == true ? {
            isValid: true
        } : {
            isValid: false,
            message: "Enter a valid URL"
        };
    }
    } else {
        if ($.trim(value).length == 0) {
        return {
            isValid: true
        }
    }
    }
};

1 个答案:

答案 0 :(得分:0)

为什么你不想使用现成的插件/库?

您可以使用jQuery Validation Plugin及其url方法。

您需要的只是:

$( "#myform" ).validate({
    rules: {
        field: {
            required: true,
            url: true
        }
    }
});

其中myform是您表单的ID。