iview implements dynamic form and custom verification time period overlap

iview implements dynamic form and custom verification time period overlap

Dynamically adding form items

iview's dynamic form addition is very simple. You just need to set the form items to an array, and push a default value when adding a new item. iview will do the rest for you.

<template lang="html">
 <div class="">

    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="rulesValidate"
      :label-width="100"
      :label-colon="true"
    >
   <FormItem
    v-for="(item, index) in formValidate.showTimeDurations"
    :key="index"
    :prop="'showTimeDurations[' + index + '].value'"
    :label="'Show time period' + (index + 1)"
   >
    <Row>
     <TimePicker
      type="timerange"
      v-model="item.value"
      placement="bottom-end"
      placeholder="Select a time period"
      style="width: 400px;"
      :disabled="isDisEdit"
      ></TimePicker>
     <Button shape="circle" icon="md-close" @click="handleRemove(index)" style="margin-left: 10px;"></Button>
    </Row>
   </FormItem>
   <FormItem style="width: 500px;" v-if="formValidate.showTimeDurations.length < 3">
    <Button type="dashed" long @click="handleAddDuration" icon="md-add">Add display period</Button>
   </FormItem>
   </Form>
 </div>
</template>

<script>
export default {
 name: 'banner_new',
 data() {
  return {
   formValidate: {
    showTimeDurations: [{value: ['','']}]
   }
  }
 },
 methods: {
  handleAddDuration() {
   this.formValidate.showTimeDurations.push({value: ['','']})
  },
  handleRemove(index) {
   this.formValidate.showTimeDurations.splice(index, 1)
  }
 }
}
</script>

<style lang="css" scoped>
</style> 

Form Validation

iview's form validation is done by adding the attribute :rules="rulesValidate" RulesValidate is the method set in methods.

Add a title form item and submit button

 <FormItem label="Name" prop="title" style="width: 500px;">
    <Input v-model="formValidate.title" :disabled="isDisEdit" :placeholder="'Please enter the name of the slideshow (up to 50 characters)'" maxlength="50" show-word-limit></Input>
  </FormItem>
  ...
  <Row type="flex" justify="start" style="margin-top: 20px;">
    <Button type="primary" style="width: 100px; margin-left: 20px;" v-if="isCanSave" @click="handleSubmit('formValidate')">Save</Button>
  </Row>
  methods: {
    handleSubmit(form) {
      // Calling the validate method will perform validation this.$refs[form].validate(validate => {
        // validate=true/false, whether the verification is successful or not})
    },
  }

Form Validation:

rulesValidate: {
  title:
    {
      required: true,
      message: 'Please fill in the name of the slideshow',
      trigger: 'blur'
    },
    {
      type: 'string',
      max: 50,
      message: 'Within 50 characters, Chinese/letters/numbers/common characters',
      trigger: 'change'
    }
  ],

It can also be written as

title: [{{ required: true, message: 'Please fill in the image name', trigger: 'blur'}}]

The verification condition is an array and multiple conditions can be written. If you need custom validation, you can define a validator in data

data() {
  const durationValitator = (rule, value, callback) => {
    if(this.isShowTimePicker && value.toString() === ',') {
      callback(new Error('Please select the display time period'));
    }else if(value[0] === value[1]) {
      callback(new Error('Please select the correct time period'))
    }else if(!showTimeDurationsJudge(this.formValidate.showTimeVOS)){
      callback(new Error('Time period cannot be repeated'))
    }else {
      callback()
    }
  };
  const durationValidate = [{ validator: durationValitator, trigger: 'blur' }];
  return {
    rulesValidate: {
      'showTimeDurations[0].value': durationValidate,
      'showTimeDurations[1].value': durationValidate,
      'showTimeDurations[2].value': durationValidate,
    }
  }
}

'showTimeDurations[0].value': durationValidate, this way of writing means validating the value of the first sub-item in the dynamic item of the form. If there are 3 sub-items, it needs to be repeated 3 times. I wonder if there is a better way of writing it? That’s it for now.

showTimeDurationsJudge is a method that verifies that time periods are repeated.

Verify that time periods overlap

First consider how to verify if there are 2 periods of time? The situation of crossing days is not considered.

The result of thinking is that the necessary and sufficient condition for two time periods not to overlap is

  • The start time (start1) and end time (end1) of the previous period (a1) must be before the start time (start2) of the next period (a2)
  • The start time (start2) and end time (end2) of the next period (a2) must be after the end time (end1) of the previous period (a1)

Meeting the above conditions can ensure that the two time periods are completely staggered.

Because the time given by the control is a string in the format of "00:00:00", I introduced the moment library to convert the string into a timestamp, which can be compared in size.

const judge = (a1,a2) => {
 let result = false
  const start1 = moment(a1[0],"HH:mm:ss").valueOf()
  const end1 = moment(a1[1],"HH:mm:ss").valueOf()
  const start2 = moment(a2[0],"HH:mm:ss").valueOf()
  const end2 = moment(a2[1],"HH:mm:ss").valueOf()

  if(start1 == start2) {
    return false
  }else if(start1 > start2) {
    result = start1 > end2
  }else {
    result = end1 < start2
  }
  return result
}

If there is overlap, it returns false; if there is no overlap, it returns true. After being able to compare two time periods, if there are more time periods, you can use a loop to compare them. The complete code is:

import moment from 'moment'

export const showTimeDurationsJudge = (durations) => {
 let judgeResult = true
 if (durations && durations.length > 1) {
  for(let i=0;i<durations.length-1;i++){
   for(let j=i+1;j < durations.length; j++) {
       judgeResult = judgeResult && judge(durations[i].value,durations[j].value)
     }
  }
 }
 return judgeResult
}

const judge = (a1,a2) => {
 let result = false
  const start1 = moment(a1[0],"HH:mm:ss").valueOf()
  const end1 = moment(a1[1],"HH:mm:ss").valueOf()
  const start2 = moment(a2[0],"HH:mm:ss").valueOf()
  const end2 = moment(a2[1],"HH:mm:ss").valueOf()

  if(start1 == start2) {
    return false
  }else if(start1 > start2) {
    result = start1 > end2
  }else {
    result = end1 < start2
  }
  return result
}

This concludes this article about how iview implements dynamic forms and custom verification time period overlap. For more relevant iview form verification content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief discussion on iview form validation
  • Summary of iview's simultaneous verification of multiple forms

<<:  JavaScript canvas text clock

>>:  jQuery implements accordion effects

Recommend

How to communicate between WIN10 system and Docker internal container IP

1. After installing the Windows version of Docker...

Vue implements file upload and download

This article example shares the specific code of ...

Native js implementation of slider interval component

This article example shares the specific code of ...

Avoid abusing this to read data in data in Vue

Table of contents Preface 1. The process of using...

Vue implements simple comment function

This article shares the specific code of Vue to i...

Detailed explanation of JavaScript state container Redux

Table of contents 1. Why Redux 2. Redux Data flow...

Detailed explanation of how to enable slow query log in MySQL database

The database enables slow query logs Modify the c...

The reason why MySQL uses B+ tree as its underlying data structure

We all know that the underlying data structure of...

mysql5.7 create user authorization delete user revoke authorization

1. Create a user: Order: CREATE USER 'usernam...

An article to understand the use of proxies in JavaScript

Table of contents What is an agent Basic knowledg...

How to set a fixed IP in Linux (tested and effective)

First, open the virtual machine Open xshell5 to c...

Tutorial on deploying springboot package in linux environment using docker

Because springboot has a built-in tomcat server, ...

WeChat applet component development: Visual movie seat selection function

Table of contents 1. Introduction 1. Component da...

IE6/7 is going to be a mess: empty text node height issue

Preface: Use debugbar to view document code in iet...