1

I have a very weird issue with my code.

I have a form builder that renders input based on input type. I have added a URL type but I cannot seem to pass a custom URL-pattern regex via the input field.

// In javascript, I access the custom `url-pattern` like:

$(function() {
  if ($('input.url_type_platform').length) {
    $('.url_type_platform').keyup(function() {
      var $th = $(this);
      if (isValidUrl($th.val(), $th.attr('url-pattern')) === 1) {
        alert("got a valid url!");
      }
    });
  }
});

function isValidUrl(url, pattern) {
  var myVariable = url;
  if (pattern.test(myVariable)) { // throws an error, TypeError: pattern.test is not a function
    return 1;
  } else {
    return -1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input url-pattern="/\b(?:(?:https?):\/\/|www\.)[-a-z0-9+&amp;@#\/%?=~_|!:,.;]*[-a-z0-9+&amp;@#\/%=~_|]/i" placeholder="" class="form-control url_type_platform" type="text" id="twitter_link" value="https://twitter.com/quickpublisher">

The issue is that when i throw in the PHP variable it works:

 var pattern = <?php echo platform::getDefaultUrlPatternRegex(); ?>
// \b(?:(?:https?):\/\/|www\.)[-a-z0-9+&amp;@#\/%?=~_|!:,.;]*[-a-z0-9+&amp;@#\/%=~_|]/i

Both console.log(<?php echo platform::getDefaultUrlPatternRegex(); ?>); and console.log(pattern); give the same result. But the latter still throws a

TypeError: pattern.test is not a function

Could there be an extra quote?

4
  • 1
    In JS, $th.attr('url-pattern') is a string, not a regex object. You need to init the regex object from your string. Commented Mar 26, 2020 at 10:38
  • Thanks for the reply @WiktorStribiżew How do i do that? Commented Mar 26, 2020 at 10:39
  • There are a lot of such questions on SO. I closed this one with one of them. Commented Mar 26, 2020 at 10:40
  • 1
    Thanks alot @WiktorStribiżew The dupe solved my issue. Commented Mar 26, 2020 at 10:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.