0

在此处输入图像描述

我有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似乎不起作用,因为我仍然可以在不提供任何价值的情况下提交表单。我曾经在单个文本字段中执行此操作,但现在它是动态的,我不知道该怎么做。

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

如何将验证规则添加到所有要键入的 URL 和必需的?

4

1 回答 1

1

v-text-fieldrules属性接受一组规则,因此您可以传递一个规则来强制执行“必需”,并传递另一个规则来验证 URL 输入:

<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',
      },
      ⋮
    }
  }
}

为了防止v-form提交,您可以SUBMIT在表单无效时禁用 - 按钮,这反映在表单的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
    },
    ⋮
  }
}

演示

于 2022-02-02T00:27:06.763 回答