简体   繁体   中英

Javascript Validate URL

I use the following code to validate URL in client side. My question is if there is a better way to do the same.. My question is not about the regex that i am using (just the overall way of writing)

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
        }
    }
    }
};

Why you don't want to use ready plugins/libraries?

You can have used jQuery Validation Plugin and its url method.

All what you need is:

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

where myform is id of your form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM