0

enter image description here

I have this.userGroups

[ { "id": 46, "group_id": 38, "url": "1", "url_num": 1, "max_iteration": 2 }, { "id": 45, "group_id": 38, "url": "2", "url_num": 1, "max_iteration": 2 }, { "id": 44, "group_id": 38, "url": "3", "url_num": 1, "max_iteration": 2 }, { "id": 43, "group_id": 38, "url": "4", "url_num": 1, "max_iteration": 2 } ]

<v-row v-for="(urlGroup, index) in urlGroups" :key="index">
    <v-col cols="12" sm="6" md="3">
        <v-text-field required v-model="urlGroup.url" label="URL" clear-icon="mdi-close-circle" clearable type="text" @click:clear="removeUrl(index)"></v-text-field>
    </v-col>
</v-row>

required doesn't seem to work because I can still submit the form without providing any value. I used to do this in a single text field, but now it's dynamic, I have no idea how to do that.

url: [(v) => !!v || 'URL is required']

How can I add a validation rule to all of them to be typed URL, and required?

code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

1

v-text-field's rules property accepts an array of rules, so you could pass one rule to enforce "required", and another to validate the URL input:

<v-text-field :rules="[rules.required, rules.url]">
const isValidUrl = value => {
  // https://stackoverflow.com/a/17773849/6277151
  const urlRegex =
    /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/gi
  return urlRegex.test(value)
}

export default {
  data() {
    return {
      rules: {
        required: value => !!value || 'Required',
        url: value => isValidUrl(value) || 'Invalid URL',
      },
      ⋮
    }
  }
}

To prevent v-form from submitting, you could disable the SUBMIT-button when the form is invalid, which is reflected in the form's value:

<v-form @submit="submit" v-model="formValid">
  ⋮
  <v-btn :disabled="!formValid" type="submit">Submit</v-btn>
</v-form>
export default {
  data() {
    return {
      formValid: false,
      ⋮
    }
  },
  methods: {
    submit() {
      if (!this.formValid) return

      // submit form here
    },
    ⋮
  }
}

demo

tony19
  • 125,647
  • 18
  • 229
  • 307