1

I have a function in Typescript testing rules for a text field in Vue using Vuetify.

Things like https://www.cnn.com, www.test.xxx fails validation. I cant seem to comprehend why...

Vuetify text-field (Vuetify v.2.2.26) :

<v-text-field label="Web site" dense :rules="webSiteRules" :readonly="!editing" v-model="profile.WebSite" />

Code (imported in .vue file - using single file components):

export function websiteRules(): ((v: string) => boolean | string)[] {
  const regexp = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gim;
  return [
    (v: string): boolean | string => !!v || 'Web site required',
    (v: string): boolean | string =>
      regexp.test(v) || 'Wrong format. use e.g. http(s)://www.cnn.com'
  ];
}
ZwapSharp
  • 11
  • 4

1 Answers1

4

I use this solution base on this answer and use the codes like this :

 <v-text-field v-model="urlString" placeholder="Enter Url" :rules="rules"> </v-text-field>

in data I write this :

<script>
export default {
  data() {
    return {
      urlString: "",
      rules: [
        (value) => !!value || "Required.",
        (value) => this.isURL(value) || "URL is not valid",
      ],
    };
  },
  methods: {
    isURL(str) {
      let url;

      try {
        url = new URL(str);
      } catch (_) {
        return false;
      }

      return url.protocol === "http:" || url.protocol === "https:";
    },
  },
};
</script>

hope to help you too :)

zoha_sh
  • 399
  • 6
  • 15