Check a text field in a form for acceptable URL's

Anonymous
Not applicable

Greetings,

I have a Marketo form with one field called sharedURL. I set this as a text field because the URL field is too restrictive, as you may have guest it is a field which allows people to input a URL. The field should only accept certain domains before moving on to the defined Landing page. Lets assume the only acceptable domains are www.marketo.com, www.marketo.com, www.marketo.com etc (all variations of the domain). I looked at multiple suggested solutions on various external sites and marketo sites but couldnt manage to tweak the code to fit my requirement. This is what I got (inserted in the HTML in a guided landing page template) my Form and field details are (if its needed). My solution did not work... any help appreciated....

"Id":6466,"Name":"sharedURL","Datatype":"string","Maxlength":512,"

<script>

(function (){

// Please include the url domains you would like to block in this list

var validDomains = [

'info.marketo.com',

'www.marketo.com',

'www.marketo.com',

'info.marketo.com',

'www.marketo.com',    

],

MktoForms2.whenReady(function (form){

form.onValidate(function(){

var url = form.vals().sharedURL;

if(url){

if(!isurlGood(url)) {

form.submitable(false);

var urlElem = form.getFormElem().find("#sharedURL");

form.showErrorMessage("You must use an approved Domain.", urlElem);

}else{

form.submitable(true);

}

}

});

});

function isurlGood(url) {

for(var i=0; i < validDomains.length; i++) {

var domain = validDomains[i];

if (url.indexOf(domain) != -1) {

return false;

}

}

return true;

}

})();

</script>

2 REPLIES 2
SanfordWhiteman
Level 10 - Community Moderator

function hostnameInList( url, list ) {

    var loc = document.createElement('a');

    loc.href = /^https?:\/\//.test(url)

      ? url

      : 'https://' + url;

    return !!list.filter( function(itm){

      return loc.hostname == itm;

    }).length;

}

Then

var allowedHostnames = ['info.example.com','marketo.com'];

hostnameInList( 'https://info.example.com/', allowedHostnames ); // true

hostnameInList( 'marketo.com#myhash', allowedHostnames ); // true

hostnameInList( 'http://marketo.com/?somequery', allowedHostnames ); // true

hostnameInList( 'https://example.com', allowedHostnames ); // false

hostnameInList( 'example.com/?somequery', allowedHostnames ); // false

(Array#filter is IE9+ so if your site still needs to support IE8 as I recall from some other posts, add a polyfill.)

MktoForms2 :: URL Hostname in Allowed List

Anonymous
Not applicable

The Wizard of Marketo has struck again.... Perfecto