1

I'm trying to check if a user-input text is a URL in VueJS. I'm not sure how to do this/what the regex would be! Could someone help? This is my code currently!

    function isValidWebUrl(url) {
  let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
  return regEx.test(url);
}

<div v-if = "regEx.test(post.postMarkdown)">
  <a>{{post.postMarkdown}}</a>
</div>
<div v-else>
  <p>{{ post.postMarkdown }}</p>
</div> -->
ckyzm
  • 45
  • 1
  • 6

1 Answers1

1

Here is a lot of regex expression for URL validation: What is the best regular expression to check if a string is a valid URL?

Simple example how it can be used for vuejs:

<template>
  <div>
    <input v-model="url" />
    <span v-if="isValid">URL invalid</span>
  </div>
</template>
const regex = '[YOUR URL REGEX GOES HERE]'

const component = {
  data () {
    return {
      url: ''
    }
  },
  computed: {
    isValid () {
      if (!this.url) return false

      return this.url.match(regex)
    }
  }
}

The code provided is like an example without testing

inser
  • 1,190
  • 8
  • 17
  • Hi, thanks so much! Do both snippets of the code go in the same place? Also the item I am trying to check for URL is actually information retrieved from the database and written as {{post.postMarkdown}}, so where would that go? – ckyzm Nov 11 '20 at 22:51
  • Where to put the code depends on approach you are using (single component, HTML templates, plain templates, etc). I think you should start to learn Vue from the beginning. https://vuejs.org/v2/guide/ – inser Nov 12 '20 at 16:18