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
  • 21
  • 1
  • 5

2 Answers2

5

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 Shobbar
  • 446
  • 8
  • 17
2
<v-text-field
    label="Url Validation"
    :rules="[rules.url]"
></v-text-field>

Must be in the scope of data

rules: {
    req: value => !!value || 'Required.',
    url: value => {
      const regex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}/gm
      return regex.test(value) || 'Invalid Url Format!!'
   },
},
munal
  • 71
  • 3