SoFunction
Updated on 2025-04-04

iView UI FORM Dynamically add form item verification rules writing example

IView UI Form Verification In-depth Learning

In the development of xxx requirements, there is an interaction that dynamically adds problem items and requires form verification. I encountered problems during the dynamic form verification process. I recorded how it was solved this time.

Form verification of UI frameworks has always been limited toform plus model, rules,existform-itemPlusprop, andpropTomodelrulesThe value corresponding to, for example:

<template>
 <Form model="questionFormData" :rules="questionRules" refs="questionFormRefs">
    <FormItem prop="question" lable="Problem Description">
      <Input v-model=""></Input>
    </FormItem>
  </Form>
</template>
<script>
  export default {
    data() {
      return {
        questionFormData: {
          question: ''
        },
        questionRules: {
          question: [{
            { required: true, message: "Not allowed to be empty", trigger: "blur" },
          }]
        }
      }
    },
    methods: {
      handleSubmit() {
        this.$refs[name].validate(async valid => {
          // valid true verification is passed, false verification is not passed      	});
      }
    }
  }
</script>

Here you wantmodel="questionFormData"Point to the corresponding data object,:rules="questionRules"Refers to the corresponding rules,prop="question"Refers to the corresponding form item to be verifiedkey(Right now); In the past, I only knew that writing this way could trigger verification rules, but the specific principles were not clear.

This time, you need to add form items dynamically, which is loop renderingFormItemBut the question is, how do I define thispropandrulesWith questions, I checked the iView official website,FORMFind the corresponding example below

:prop="'items.' + index + '.value'"
:rules="{required: true, message: 'Item ' +  +' can not be empty', trigger: 'blur'}"

It turns out that it can be added dynamicallyprop andrules, as long aspropJust point to the corresponding subscript, readjust the code

<template>
<Form model="questionFormData" :rules="questionRules" refs="questionFormRefs">
    <FormItem 
        v-for="(item, index) of "
        :prop="'questions.' + index +'.question'"
        :rules="{required: true, message: 'question' + (index + 1) + 'Not allowed', trigger: 'blur'}"
        :lable="'question' + (index + 1) +'describe"
    >
    <Input v-model="[index]"></Input>
  </FormItem>
</Form>
</template>
<script>
	export default {
    data() {
      return {
        questionFormData: {
          questions: [{
            id: 1,
            question: 'Question 1'
          }, {
            id: 2,
            question: 'Question 2'
          }],
        },
        questionRules: {
        }
      }
    }
  }
</script>

After the above adjustments, the verification of dynamic forms has also taken effect. Please note here.propThe value must bequestionFormDataThe key, i.e.questions.[index].question, as above first itempropValue ofquestions., if changed toitems.It will not take effect. Report[iView warn]: please transfer a valid prop path to form item!, means,propThe value ofquestionFormDataNot found in.

The verification of dynamic forms has finally been solved, butquestions.[index].questionSome questions,FormItemHow to recognize strings and withquestionFormDataThe value of . Let's take a look with questions<FormItem>Source code.

Explore the principle

turn upFormItemSource code, pathnode_modules/view-design/src/components/form/, find the answer in the source code:

computed: {
  fieldValue () {
    // FormInstance is an instance of the current Form, get the model, that is, questionFormData    const model = ;
    if (!model || !) { return; }
		// The prop here is questions.    let path = ;
    // If you encounter:, replace it with a point, such as questions: -> questions.    if ((':') !== -1) {
      path = (/:/, '.');
    }
    // Get the value of questions. in questionFormData    return getPropByPath(model, path).v;
  },
},
function getPropByPath(obj, path) {
  // tempObj = questionFormData
  let tempObj = obj;
  // Replace the brackets with. For example questions[0][question] -> questions.  path = (/\[(\w+)\]/g, '.$1'); 
  // Replace the first one., .questions. -> questions. Finally processed into this format  path = (/^\./, '');
  // Split into an array to get ['questions','0','question']  let keyArr = ('.');
  let i = 0;
	// Check the function of the code here with i = 0  for (let len = ; i &lt; len - 1; ++i) {
    // key = questions
    let key = keyArr[i];
    // questions In questionFormData, enter the code block that is true    if (key in tempObj) {
      // tempObj = questions
      tempObj = tempObj[key];
    } else {
      throw new Error('[iView warn]: please transfer a valid prop path to form item!');
    }
  }
  return {
    o: tempObj, // { id: 1, question: 'question1' }    k: keyArr[i], // question
    v: tempObj[keyArr[i]] // Question 1  };
 }

It turns out that it is divided into data through., and the value of the array is accessed in the form of a key.modelObject, match the corresponding value. When the value does not match, it will be thrown'[iView warn]: please transfer a valid prop path to form item!'mistake.

Summary: By reading the source code, we can find that dynamically adding verification rules can be used more than justkey.[index].keyYou can also use the[key][index][key]Defining stringsprop, but be careful **keyTomodelIn-housekeyConsistent**

The above is the detailed content of the example of the dynamic addition of form item verification rules for iView UI FORM. For more information about the form item verification rules for iView UI FORM, please pay attention to my other related articles!