Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

URL validation including domain

CN-L
Tera Contributor

Hi Community,

 

I'm after some collective assistance to help me with an onChange Catalog Client Script please.

 

Goal: When a user enters a URL into a single line text variable [provide_url], I want to ensure they have entered a valid URL including the domain.

 

What I've Done: I created the below script which validates successfully if the user enters content that starts with http, https, or www however, I'd like to expand this if possible to check for a domain at the end i.e. .co.uk, .com, etc.

 

Current script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var url = g_form.getValue('provide_url');

    var re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;

    if (!re.test(url)) {
        g_form.showFieldMsg('provide_url', 'Please enter a valid URL');
        return false;
    }
}

 

I'm assuming that I need to add some extra logic to end of this statement but my brain is failing to work it out:

var re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;

 

Any help would be greatly appreciated!

4 REPLIES 4

Kieran Anson
Kilo Patron

Rather than using an onChange client script, have you looked into Variable Regex Validation?

 

SN provide an OOTB regex validation for URLs

 

Field validation: Regular Expressions - ServiceNow Community

 

OOTB Regex: (((ftp|http|https):\/\/)|(www\.))([-\w\.\/#$\?=+@&%_:;]+)

 

A copy of the OOTB regex could be created, with an additional capture group

^(((ftp|http|https):\/\/)|(www\.))([-\w\.\/#$\?=+@&%_:;]+)(?:\.com|\.co\.uk)$

I did take a look at the OOTB regex validation however I didn't think of creating a copy *facepalm*

 

Because of the sheer number of possible domains, is there a way to validate that the URL ends with 2-3 characters . 2-3 characters, rather than listing them out?

Tanushree Maiti
Kilo Patron

Hi @CN-L 

 

Try with this regex. It will work.

 

^(https?:\/\/)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$

 

 

Please mark this response as Helpful & Accept it as solution if it assisted you with your question.
Regards
Tanushree Maiti
ServiceNow Technical Architect
Linkedin:

CN-L
Tera Contributor

Thanks to @Kieran Anson and @Tanushree Maiti - after some trial and error following your suggestions, I was able to get this working in my PDI with the following regex:

 

^(((ftp|http|https):\/\/)|(www\.))([-\w\.\/#$\?=+@&%_:;])+(\.[a-z]{2,})$