javascriptjqueryajaxtrumbowyg

Allow only HTTPS URL in input field


I am using Trumbowyg, a WYSIWYG JavaScript editor which allows rendering images by pasting a URL.

So you paste the URL in the field and then click the Confirm button and then it appends the image in the editor (you can test it out here)

I want to prevent adding images that are not HTTPS. So if someone inserts a URL that is not HTTPS, I want to prevent appending the image when they click Confirm.

This is the function for the image URL (from the docs):

insertImage: function () {
            var t = this;
            t.saveRange();

            var options = {
                url: {
                    label: 'URL',
                    required: true
                },
                alt: {
                    label: t.lang.description,
                    value: t.getRangeText()
                }
            };

            if (t.o.imageWidthModalEdit) {
                options.width = {};
            }

            t.openModalInsert(t.lang.insertImage, options, function (v) { // v are values
                t.execCmd('insertImage', v.url);
                var $img = $('img[src="' + v.url + '"]:not([alt])', t.$box);
                $img.attr('alt', v.alt);

                if (t.o.imageWidthModalEdit) {
                    $img.attr({
                        width: v.width
                    });
                }

                t.syncCode();
                t.$c.trigger('tbwchange');

                return true;
            });
        }

Any idea how I can amend this function to only allow HTTPS inputs?


Solution

  • A good solution for this problem would be to use Regular Expressions, or short: Regex.

    Regex allowes you to verify if a string actually contains the data you're expecting. A downside of regex though is that it's CPU intensive. That's why regex should only be used if no other function is available to do the job. As it happens, there's another function available for this: substr().

    Therefor the better solution would be:

    var url = v.url;
    
    if(!url.substr(0,7) === 'https://'){
        return false;
    }
    

    Though learning regex is definitely helpfull in the long run. A website that will help you a lot with this is https://regex101.com/. You'll eventually run into situations where other solutions simply aren't available. Therefor testing with regex is a good way to learn. Using regex, the solution would be:

    var url = v.url;
    
    if(!url.match(/^https:\/\//)){
        return false;
    }