Field not required but if user entered a value it must be meeting some rules (vuetify rules)

Viewed 1351

I am trying to enter a validation for a field that accept url, the field not required but if user entered a value it must meet url regex.

so I tried the following code

<v-text-field height="34px" v-model="website" single-line outline placeholder="http://"  :rules="urlRules"></v-text-field>

this attribute :rules="urlRules" refer to a bulk of rules that I give in my vue object

 urlRules: [
        v => !!v || 'required',
        v => /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi.test(v) || 'Please enter a correct URL to your website'
      ],

I want to change the validation in the rule object to make it not required but if user entered a url it must be correct

4 Answers

You can do it like below

urlRules: [
    v => (v && v.length > 0 && !YOUR_REGEXP.test(v)) ? 'Please enter a correct URL to your website' : true
],

This is how I manage to validate non required fields with Vuetify:

urlRules: [
    (v) => ( !v || YOUR_REGEX.test(v) ) || 'Please enter a correct URL to your website'
  ],

Check the !v. I am validating first, that if nothing is passed, will trigger a true value, this means, will not be required. But if something is passed, will check your regex or whatever expression you want to place.

There are other options, like an if else inside the rules, but i prefer this (prettier).

I solved this by maintaining separate validation functions as follows:

export const emailFormat = v =>
  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
  "E-mail must be valid";

export const emptyEmailFormat = v => {
  if (v && v.length > 0) {
    return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
      "E-mail must be valid";
  } else {
    return true
  }
}

emailRules = {
    isRequired: this.question.mandatory ? required : true,
    emailFormat: this.question.mandatory ? emailFormat : emptyEmailFormat
};

I got this idea after posting this question

I used a regex that accept an empty value with the pattern I want

here is what I used

urlRules: [

        v => /^$|[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi.test(v) || 'Please enter a correct URL to your website'
      ],

so if there is a better answer share it with me plz

Related