How to validate a URL in Vee-validate 3.0?

Viewed 2573

I don't find the option to validate a URL anymore.

What would be the best way to implement it or to add it to vee-validate 3.0?

I guess I have to extend the current vee-validate:

import { ValidationObserver, ValidationProvider, localize, extend as VeeExtend } from 'vee-validate/dist/vee-validate.full';

and then something like

const urlFixRule = (value) => {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(value);
};
VeeExtend('url', {
    validate: (val) => urlFixRule(val),
    message: i18n.t('custom_vee_validate.incorrect_url')
});
  • Which would be the best way of validating the URL?
  • Why has such a useful feature been removed?
2 Answers

@mojtaba answer is completly correct. Therefore we could improve on his answer on adding the rule globally available. This would allow to re-use the rule anywhere in our application

import { extend } from "vee-validate";

extend('url', {
  validate(value: string | null | undefined): boolean {
    if (value) {
      return /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(value);
    }

    return false;
  },
  message: 'This value must be a valid URL',
})

Then in our component we could simply do:

<input rules="url"/>

Vee Validate has regex rule, as you know most of the validations are created by regular expiration. so you can easily create rules that you need without extending.

Document Link

Example for URL validating:

<ValidationProvider :rules="{ regex: /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ }" v-slot="{ errors }">
    <input type="text" v-model="value">
    <span>{{ errors[0] }}</span>
</ValidationProvider>
Related