This is the 11th day of my participation in the August Gwen Challenge. Check out the details: [August Gwen Challenge](juejin.cn/post/698796… “Juejin. Cn/post / 698796…” )

Element is a component library that we often use in the development process, and the form validation is no stranger to us. In addition to regular form validation, we also need to customize validation rules, or dynamic form validation. Some students will separate the form form into a child component. So how to trigger the child component validation in the parent component? How do I clear validation after resetting the form?

1. Verification of conventional forms:

According to Element’s website, the Form component provides Form validation, requiring only passingrulesAttribute is passed to the convention’s validation rule, and the form-item’spropProperty to the name of the field to be verified. Rules is an object in which each attribute corresponds to an array and each item of the array corresponds to a verification rule, indicating that we can formulate multiple verification rules.

Picture: a screenshot of the official website

Type refers to the type of the validator, similar to array format education.

Common types arestring: string type (default);number: Numeric type;boolean: Boolean type;method: function type;regexp: regular expression;integer: integer;float: double precision floating point number;array: array type;object: Object type;enum: enumeration value;date: Date format;url: Url format;hex: hexadecimal number;email: Email format;any: Any type

Required means whether it is required or optional.

A hint given when the mesaage value does not meet the expected condition.

Trigger type: blur is triggered when the focus is out of focus.

Note: For date pickers, we use the “date” type for type, but if format is changed to “YYYY-MM-DD”, type should be “string” or no type

2. Verify the custom form

The above general form validation will satisfy most of the requirements, but there are some more stringent validation rules that you can customize to validate

The value of the Validator is a function with our own custom validation rules. Rule collects the attributes of the validation rule. Value stands for value, and callback is a callback function that must be called whether or not it succeeds

3. Verification of dynamic forms

Sometimes we need to render the form dynamically based on the value returned by the back end. In this case, if we write rules, we need to include all possible situations, and the elements of the form will be different each time. At this point we need to add attribute rules to every element that can be rendered

To loop through the data, we need to determine the type of each form element according to operationType and whether to validate according to ifRequire

    <Form :ref="item.attrName" :model="item" :label-width="180">
        <FormItem
          v-for="(item, index) in attrsList" 
          :key="index"
          :label="item.attrName"
          :rules="{
            required: item.ifRequire,
            operationType: item.operationType,
            attrName: attrName,
            validator: (rule, value, callback) => {
              verSaleStepNum(rule, value,callback);
            },
          }"
          prop="value"
        >
          <Select v-if="item.operationType == '10'" v-model="item.value" multiple class="input-width">
            <Option
              v-for="i in item.itemCodeDto"
              :value="i.itemCode"
              :key="i.itemCode"
              >{{ i.itemName }}</Option
            >
          </Select>
          <Input v-if="item.operationType == '20' class="input-width" v-model="item.value"></Input>
        </FormItem>
      </Form>
Copy the code

Custom validation: the rule defines the properties we set. We can use the rule-operationType method to collect the properties we defined above, such as the concatenation hint (dynamic we can’t determine what label is).

verSaleStepNum(rule, value, callback) { const message = rule.operationType === "10" ? 'Please select ${rule-attrname}' : ${rule-.attrName} 'if (rule-required) {// Type check if (this.isarray (value)) {// Array type if (value.length <= 0) { callback(new Error(message)); } } else { if (typeof value === "string") { if (this.checkNull(value)) { callback(new Error(message)); } } } } callback(); },Copy the code

4. Verification of sub-component forms

To encapsulate validation in a method, the parent component gets the validation result of the child component with the method name this,$res.xxx

Method 1. The parent component validates the child component form with a callback

** Subcomponent code:

$refs["formInline"]. Validate((valid) => {callback(valid); });Copy the code

Parent component code

  let inforValid = false
  this.$refs.infoList.infoListValidate((valid) => {
        inforValid = valid;
   });
Copy the code

Method 2. Return result of child component form validation

Subcomponent code

InfoListValidate (callback) {let status = false this.$refs["formInline"].validate((valid) => { status = valid }); return statusCopy the code

Parent component code

  let inforValid = false
  this.$refs.infoList.infoListValidate((valid) => {
        inforValid = valid;
   });
Copy the code